Laravel - Convert a base64 string to a valid image












0















To give you a grasp of what I am trying to do, here is my current code



This code is run when a post request is made to specific URL



public function uploadImage(Request $request) {
$request->file = base64_decode(explode(',', $request->file)[1]);

$request->validate([
'file' => 'image|required|mimes:jpg,png',
]);

$image = $request->file('file');

$complete = $image->getClientOriginalName();
$name = pathinfo($complete, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$storageName = $name.'_'.time().'.'.$extension;

Storage::disk('public')->put($storageName, File::get($image));

return Storage::disk('public')->path($storageName);
}


On the first line I am trying to be smart and first decode the base64 to a file (if I am correct?).



Next is a validation to validate if the file parameter in the request exists, is an image, and is a .jpg or .png



(The next lines is just about saving the "image" to the filesystem)



But the validation won't pass because the file parameter is not an image. So my question is: is it possible to convert a base64 string to a valid image in Laravel? If it is, how can this be achieved?










share|improve this question


















  • 1





    Look at PHP's GD library... specifically php.net/manual/en/function.imagecreatefromstring.php

    – ArtisticPhoenix
    Nov 13 '18 at 19:52


















0















To give you a grasp of what I am trying to do, here is my current code



This code is run when a post request is made to specific URL



public function uploadImage(Request $request) {
$request->file = base64_decode(explode(',', $request->file)[1]);

$request->validate([
'file' => 'image|required|mimes:jpg,png',
]);

$image = $request->file('file');

$complete = $image->getClientOriginalName();
$name = pathinfo($complete, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$storageName = $name.'_'.time().'.'.$extension;

Storage::disk('public')->put($storageName, File::get($image));

return Storage::disk('public')->path($storageName);
}


On the first line I am trying to be smart and first decode the base64 to a file (if I am correct?).



Next is a validation to validate if the file parameter in the request exists, is an image, and is a .jpg or .png



(The next lines is just about saving the "image" to the filesystem)



But the validation won't pass because the file parameter is not an image. So my question is: is it possible to convert a base64 string to a valid image in Laravel? If it is, how can this be achieved?










share|improve this question


















  • 1





    Look at PHP's GD library... specifically php.net/manual/en/function.imagecreatefromstring.php

    – ArtisticPhoenix
    Nov 13 '18 at 19:52
















0












0








0








To give you a grasp of what I am trying to do, here is my current code



This code is run when a post request is made to specific URL



public function uploadImage(Request $request) {
$request->file = base64_decode(explode(',', $request->file)[1]);

$request->validate([
'file' => 'image|required|mimes:jpg,png',
]);

$image = $request->file('file');

$complete = $image->getClientOriginalName();
$name = pathinfo($complete, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$storageName = $name.'_'.time().'.'.$extension;

Storage::disk('public')->put($storageName, File::get($image));

return Storage::disk('public')->path($storageName);
}


On the first line I am trying to be smart and first decode the base64 to a file (if I am correct?).



Next is a validation to validate if the file parameter in the request exists, is an image, and is a .jpg or .png



(The next lines is just about saving the "image" to the filesystem)



But the validation won't pass because the file parameter is not an image. So my question is: is it possible to convert a base64 string to a valid image in Laravel? If it is, how can this be achieved?










share|improve this question














To give you a grasp of what I am trying to do, here is my current code



This code is run when a post request is made to specific URL



public function uploadImage(Request $request) {
$request->file = base64_decode(explode(',', $request->file)[1]);

$request->validate([
'file' => 'image|required|mimes:jpg,png',
]);

$image = $request->file('file');

$complete = $image->getClientOriginalName();
$name = pathinfo($complete, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$storageName = $name.'_'.time().'.'.$extension;

Storage::disk('public')->put($storageName, File::get($image));

return Storage::disk('public')->path($storageName);
}


On the first line I am trying to be smart and first decode the base64 to a file (if I am correct?).



Next is a validation to validate if the file parameter in the request exists, is an image, and is a .jpg or .png



(The next lines is just about saving the "image" to the filesystem)



But the validation won't pass because the file parameter is not an image. So my question is: is it possible to convert a base64 string to a valid image in Laravel? If it is, how can this be achieved?







php laravel laravel-5






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 19:31









FlyingUnderpantsFlyingUnderpants

4310




4310








  • 1





    Look at PHP's GD library... specifically php.net/manual/en/function.imagecreatefromstring.php

    – ArtisticPhoenix
    Nov 13 '18 at 19:52
















  • 1





    Look at PHP's GD library... specifically php.net/manual/en/function.imagecreatefromstring.php

    – ArtisticPhoenix
    Nov 13 '18 at 19:52










1




1





Look at PHP's GD library... specifically php.net/manual/en/function.imagecreatefromstring.php

– ArtisticPhoenix
Nov 13 '18 at 19:52







Look at PHP's GD library... specifically php.net/manual/en/function.imagecreatefromstring.php

– ArtisticPhoenix
Nov 13 '18 at 19:52














3 Answers
3






active

oldest

votes


















0














Laravel can't resolve your base 64 string to a file, hence the failure of the file validator. You also won't be able to access your data with ->file('file'), since again, you're not sending over a valid file upload.



Instead, you could do your own simple string check (perhaps index of data:image or preferably something more extensive, like imagecreatefromstring) or look into writing a custom Laravel validation rule, and then save the sent string into a file with file_put_contents.



If you're actually wanting to do a file upload and convert that to base 64 on the server side, then you'll want to use an <input type="file">. From there, you'll be able to use built-in Laravel validation and file storage functions. Refer to this extensive guide. Once you've gotten your file, you can convert it to base64 using base64_encode (see this answer for a more thorough guide).



I realize this answer wasn't very specific, but if you clarify exactly what you're trying to do, I can give more hands-on guidance.






share|improve this answer































    0















    You can valid image base64

    please follow me step by step :




    1 . Go to folder yourProjectNameappProvidersAppServiceProvider.php

    2 . copy this code and past in this file at function boot()




    Validator::extend('is_image', function ($attribute, $value, $parameters, $validator) {
    preg_match_all('/([^.]+).([a-zA-Z]+)/',$value,$matchedExt);
    if (isset($matchedExt[2][0]) && in_array($matchedExt[2][0],$parameters)) return true;
    preg_match_all('/data:image/([a-zA-Z]+);base64/',$value,$matched);
    $ext = isset($matched[1][0]) ? $matched[1][0] : false;
    print_r($value);
    return in_array($ext,$parameters) ? true : false;
    });



    1. Go to your function uploadImage() and past this code



    public function uploadImage(Request $request) {

    $request->validate([
    'file' => 'image|required|is_image:jpg,png',
    ]);

    $image = $request->file('file');

    $complete = $image->getClientOriginalName();
    $name = pathinfo($complete, PATHINFO_FILENAME);
    $extension = $image->getClientOriginalExtension();
    $storageName = $name.'_'.time().'.'.$extension;

    Storage::disk('public')->put($storageName, File::get($image));

    return Storage::disk('public')->path($storageName);
    }


    I hope I'll solve the problem for you






    share|improve this answer































      0














      I'm using this code to convert a base64 string to an image :



          public function getImage($img, $pid)
      {
      if($img == "")
      return null;
      $imagecode = base64_decode($img);

      $directory = public_path('img/uploads/x' . $pid);
      if (!file_exists($directory))
      File::makeDirectory($directory);
      $id = uniqid('img_');
      $filename = time() . '-' . $id . '.png';
      $path = public_path('img/uploads/product_img/p' . $pid . '/' . $filename);
      $tpath = public_path('img/uploads/product_img/p' . $pid . '/small-' . $filename);

      try {
      $image = Image::make($imagecode)->widen(600, function ($constraint) {
      $constraint->upsize();
      })->save($path);
      $image->fit(200, 200)->save($tpath);
      } catch (Exception $e) {
      return null;
      }

      return "x" . $pid . "/" . $filename;
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53288266%2flaravel-convert-a-base64-string-to-a-valid-image%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Laravel can't resolve your base 64 string to a file, hence the failure of the file validator. You also won't be able to access your data with ->file('file'), since again, you're not sending over a valid file upload.



        Instead, you could do your own simple string check (perhaps index of data:image or preferably something more extensive, like imagecreatefromstring) or look into writing a custom Laravel validation rule, and then save the sent string into a file with file_put_contents.



        If you're actually wanting to do a file upload and convert that to base 64 on the server side, then you'll want to use an <input type="file">. From there, you'll be able to use built-in Laravel validation and file storage functions. Refer to this extensive guide. Once you've gotten your file, you can convert it to base64 using base64_encode (see this answer for a more thorough guide).



        I realize this answer wasn't very specific, but if you clarify exactly what you're trying to do, I can give more hands-on guidance.






        share|improve this answer




























          0














          Laravel can't resolve your base 64 string to a file, hence the failure of the file validator. You also won't be able to access your data with ->file('file'), since again, you're not sending over a valid file upload.



          Instead, you could do your own simple string check (perhaps index of data:image or preferably something more extensive, like imagecreatefromstring) or look into writing a custom Laravel validation rule, and then save the sent string into a file with file_put_contents.



          If you're actually wanting to do a file upload and convert that to base 64 on the server side, then you'll want to use an <input type="file">. From there, you'll be able to use built-in Laravel validation and file storage functions. Refer to this extensive guide. Once you've gotten your file, you can convert it to base64 using base64_encode (see this answer for a more thorough guide).



          I realize this answer wasn't very specific, but if you clarify exactly what you're trying to do, I can give more hands-on guidance.






          share|improve this answer


























            0












            0








            0







            Laravel can't resolve your base 64 string to a file, hence the failure of the file validator. You also won't be able to access your data with ->file('file'), since again, you're not sending over a valid file upload.



            Instead, you could do your own simple string check (perhaps index of data:image or preferably something more extensive, like imagecreatefromstring) or look into writing a custom Laravel validation rule, and then save the sent string into a file with file_put_contents.



            If you're actually wanting to do a file upload and convert that to base 64 on the server side, then you'll want to use an <input type="file">. From there, you'll be able to use built-in Laravel validation and file storage functions. Refer to this extensive guide. Once you've gotten your file, you can convert it to base64 using base64_encode (see this answer for a more thorough guide).



            I realize this answer wasn't very specific, but if you clarify exactly what you're trying to do, I can give more hands-on guidance.






            share|improve this answer













            Laravel can't resolve your base 64 string to a file, hence the failure of the file validator. You also won't be able to access your data with ->file('file'), since again, you're not sending over a valid file upload.



            Instead, you could do your own simple string check (perhaps index of data:image or preferably something more extensive, like imagecreatefromstring) or look into writing a custom Laravel validation rule, and then save the sent string into a file with file_put_contents.



            If you're actually wanting to do a file upload and convert that to base 64 on the server side, then you'll want to use an <input type="file">. From there, you'll be able to use built-in Laravel validation and file storage functions. Refer to this extensive guide. Once you've gotten your file, you can convert it to base64 using base64_encode (see this answer for a more thorough guide).



            I realize this answer wasn't very specific, but if you clarify exactly what you're trying to do, I can give more hands-on guidance.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 13 '18 at 19:56









            Sheng SlogarSheng Slogar

            897614




            897614

























                0















                You can valid image base64

                please follow me step by step :




                1 . Go to folder yourProjectNameappProvidersAppServiceProvider.php

                2 . copy this code and past in this file at function boot()




                Validator::extend('is_image', function ($attribute, $value, $parameters, $validator) {
                preg_match_all('/([^.]+).([a-zA-Z]+)/',$value,$matchedExt);
                if (isset($matchedExt[2][0]) && in_array($matchedExt[2][0],$parameters)) return true;
                preg_match_all('/data:image/([a-zA-Z]+);base64/',$value,$matched);
                $ext = isset($matched[1][0]) ? $matched[1][0] : false;
                print_r($value);
                return in_array($ext,$parameters) ? true : false;
                });



                1. Go to your function uploadImage() and past this code



                public function uploadImage(Request $request) {

                $request->validate([
                'file' => 'image|required|is_image:jpg,png',
                ]);

                $image = $request->file('file');

                $complete = $image->getClientOriginalName();
                $name = pathinfo($complete, PATHINFO_FILENAME);
                $extension = $image->getClientOriginalExtension();
                $storageName = $name.'_'.time().'.'.$extension;

                Storage::disk('public')->put($storageName, File::get($image));

                return Storage::disk('public')->path($storageName);
                }


                I hope I'll solve the problem for you






                share|improve this answer




























                  0















                  You can valid image base64

                  please follow me step by step :




                  1 . Go to folder yourProjectNameappProvidersAppServiceProvider.php

                  2 . copy this code and past in this file at function boot()




                  Validator::extend('is_image', function ($attribute, $value, $parameters, $validator) {
                  preg_match_all('/([^.]+).([a-zA-Z]+)/',$value,$matchedExt);
                  if (isset($matchedExt[2][0]) && in_array($matchedExt[2][0],$parameters)) return true;
                  preg_match_all('/data:image/([a-zA-Z]+);base64/',$value,$matched);
                  $ext = isset($matched[1][0]) ? $matched[1][0] : false;
                  print_r($value);
                  return in_array($ext,$parameters) ? true : false;
                  });



                  1. Go to your function uploadImage() and past this code



                  public function uploadImage(Request $request) {

                  $request->validate([
                  'file' => 'image|required|is_image:jpg,png',
                  ]);

                  $image = $request->file('file');

                  $complete = $image->getClientOriginalName();
                  $name = pathinfo($complete, PATHINFO_FILENAME);
                  $extension = $image->getClientOriginalExtension();
                  $storageName = $name.'_'.time().'.'.$extension;

                  Storage::disk('public')->put($storageName, File::get($image));

                  return Storage::disk('public')->path($storageName);
                  }


                  I hope I'll solve the problem for you






                  share|improve this answer


























                    0












                    0








                    0








                    You can valid image base64

                    please follow me step by step :




                    1 . Go to folder yourProjectNameappProvidersAppServiceProvider.php

                    2 . copy this code and past in this file at function boot()




                    Validator::extend('is_image', function ($attribute, $value, $parameters, $validator) {
                    preg_match_all('/([^.]+).([a-zA-Z]+)/',$value,$matchedExt);
                    if (isset($matchedExt[2][0]) && in_array($matchedExt[2][0],$parameters)) return true;
                    preg_match_all('/data:image/([a-zA-Z]+);base64/',$value,$matched);
                    $ext = isset($matched[1][0]) ? $matched[1][0] : false;
                    print_r($value);
                    return in_array($ext,$parameters) ? true : false;
                    });



                    1. Go to your function uploadImage() and past this code



                    public function uploadImage(Request $request) {

                    $request->validate([
                    'file' => 'image|required|is_image:jpg,png',
                    ]);

                    $image = $request->file('file');

                    $complete = $image->getClientOriginalName();
                    $name = pathinfo($complete, PATHINFO_FILENAME);
                    $extension = $image->getClientOriginalExtension();
                    $storageName = $name.'_'.time().'.'.$extension;

                    Storage::disk('public')->put($storageName, File::get($image));

                    return Storage::disk('public')->path($storageName);
                    }


                    I hope I'll solve the problem for you






                    share|improve this answer














                    You can valid image base64

                    please follow me step by step :




                    1 . Go to folder yourProjectNameappProvidersAppServiceProvider.php

                    2 . copy this code and past in this file at function boot()




                    Validator::extend('is_image', function ($attribute, $value, $parameters, $validator) {
                    preg_match_all('/([^.]+).([a-zA-Z]+)/',$value,$matchedExt);
                    if (isset($matchedExt[2][0]) && in_array($matchedExt[2][0],$parameters)) return true;
                    preg_match_all('/data:image/([a-zA-Z]+);base64/',$value,$matched);
                    $ext = isset($matched[1][0]) ? $matched[1][0] : false;
                    print_r($value);
                    return in_array($ext,$parameters) ? true : false;
                    });



                    1. Go to your function uploadImage() and past this code



                    public function uploadImage(Request $request) {

                    $request->validate([
                    'file' => 'image|required|is_image:jpg,png',
                    ]);

                    $image = $request->file('file');

                    $complete = $image->getClientOriginalName();
                    $name = pathinfo($complete, PATHINFO_FILENAME);
                    $extension = $image->getClientOriginalExtension();
                    $storageName = $name.'_'.time().'.'.$extension;

                    Storage::disk('public')->put($storageName, File::get($image));

                    return Storage::disk('public')->path($storageName);
                    }


                    I hope I'll solve the problem for you







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 13 '18 at 19:58









                    عبدالرزاق أوكساعبدالرزاق أوكسا

                    13




                    13























                        0














                        I'm using this code to convert a base64 string to an image :



                            public function getImage($img, $pid)
                        {
                        if($img == "")
                        return null;
                        $imagecode = base64_decode($img);

                        $directory = public_path('img/uploads/x' . $pid);
                        if (!file_exists($directory))
                        File::makeDirectory($directory);
                        $id = uniqid('img_');
                        $filename = time() . '-' . $id . '.png';
                        $path = public_path('img/uploads/product_img/p' . $pid . '/' . $filename);
                        $tpath = public_path('img/uploads/product_img/p' . $pid . '/small-' . $filename);

                        try {
                        $image = Image::make($imagecode)->widen(600, function ($constraint) {
                        $constraint->upsize();
                        })->save($path);
                        $image->fit(200, 200)->save($tpath);
                        } catch (Exception $e) {
                        return null;
                        }

                        return "x" . $pid . "/" . $filename;
                        }





                        share|improve this answer




























                          0














                          I'm using this code to convert a base64 string to an image :



                              public function getImage($img, $pid)
                          {
                          if($img == "")
                          return null;
                          $imagecode = base64_decode($img);

                          $directory = public_path('img/uploads/x' . $pid);
                          if (!file_exists($directory))
                          File::makeDirectory($directory);
                          $id = uniqid('img_');
                          $filename = time() . '-' . $id . '.png';
                          $path = public_path('img/uploads/product_img/p' . $pid . '/' . $filename);
                          $tpath = public_path('img/uploads/product_img/p' . $pid . '/small-' . $filename);

                          try {
                          $image = Image::make($imagecode)->widen(600, function ($constraint) {
                          $constraint->upsize();
                          })->save($path);
                          $image->fit(200, 200)->save($tpath);
                          } catch (Exception $e) {
                          return null;
                          }

                          return "x" . $pid . "/" . $filename;
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            I'm using this code to convert a base64 string to an image :



                                public function getImage($img, $pid)
                            {
                            if($img == "")
                            return null;
                            $imagecode = base64_decode($img);

                            $directory = public_path('img/uploads/x' . $pid);
                            if (!file_exists($directory))
                            File::makeDirectory($directory);
                            $id = uniqid('img_');
                            $filename = time() . '-' . $id . '.png';
                            $path = public_path('img/uploads/product_img/p' . $pid . '/' . $filename);
                            $tpath = public_path('img/uploads/product_img/p' . $pid . '/small-' . $filename);

                            try {
                            $image = Image::make($imagecode)->widen(600, function ($constraint) {
                            $constraint->upsize();
                            })->save($path);
                            $image->fit(200, 200)->save($tpath);
                            } catch (Exception $e) {
                            return null;
                            }

                            return "x" . $pid . "/" . $filename;
                            }





                            share|improve this answer













                            I'm using this code to convert a base64 string to an image :



                                public function getImage($img, $pid)
                            {
                            if($img == "")
                            return null;
                            $imagecode = base64_decode($img);

                            $directory = public_path('img/uploads/x' . $pid);
                            if (!file_exists($directory))
                            File::makeDirectory($directory);
                            $id = uniqid('img_');
                            $filename = time() . '-' . $id . '.png';
                            $path = public_path('img/uploads/product_img/p' . $pid . '/' . $filename);
                            $tpath = public_path('img/uploads/product_img/p' . $pid . '/small-' . $filename);

                            try {
                            $image = Image::make($imagecode)->widen(600, function ($constraint) {
                            $constraint->upsize();
                            })->save($path);
                            $image->fit(200, 200)->save($tpath);
                            } catch (Exception $e) {
                            return null;
                            }

                            return "x" . $pid . "/" . $filename;
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 14 '18 at 6:33









                            RezasysRezasys

                            558




                            558






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53288266%2flaravel-convert-a-base64-string-to-a-valid-image%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Academy of Television Arts & Sciences

                                L'Équipe

                                1995 France bombings