Search code examples
phpandroidgdimagick

GD/Imagick doesn't save my image


I want to send an image from android and save it trought a php code in my server. Because I need to protect my server I need to reprocess the image so I have to use GD or Imagick. Image is sent encoded in base64. In the php file is decoded and if I use:

$img=base64_decode($img);
$file = fopen('test.jpg', 'wb');
fwrite($file, $img);
fclose($file);

image is saved in the server. If I use Imagick or GD my image isn't saved and the php files returns nothing, even if I insert an echo after it. Any help? In GD I was using:

$img=base64_decode($img);
$imageinfo = getimagesize($img);
if($imageinfo['mime'] == 'image/gif'{
    $img = @imagecreatefromjpeg($img);
    imagejpeg($img, ""testt.jpg", 80);
}

and in Imagick:

$img=base64_decode($img);
$img = imagick($img); //neither if I use a path of an image saved in my server 
                      //works
$mime = mime_content_type($img);
    switch ($mime):
        case 'image/jpeg':
            $ext = '.jpg';
            break;
    endswitch;

$img->stripImage();
$img->writeImage(""testt".$ext);
$img->clear();
$img->destroy();

Solution

  • imagick only works on files, you can't give a handle to it unfortunately, so:

    $img=base64_decode($img);
    $filename = tempnam(sys_get_temp_dir(), 'tempimage_'); 
    $file = fopen($filename, 'wb');
    fwrite($file, $img);
    fclose($file);
    
    $img = imagick($filename);  
    $mime = mime_content_type($img);
        switch ($mime):
            case 'image/jpeg':
                $ext = '.jpg';
                break;
       endswitch;
    
    $img->stripImage();
    $img->writeImage("testt".$ext);
    $img->clear();
    $img->destroy();
    

    This, in theory, should work.