laravelbase64intervention

Saving animated gif with image intervention


I am trying to upload animated gif as user avatar. These images are converted to base64 through javascript and then are uploaded using image intervention.

$img = Image::make(file_get_contents($file));
$mime = $img->mime();
if ($mime == 'image/jpeg')
    $ext= '.jpg';
elseif ($mime == 'image/png')
    $ext= '.png';
elseif ($mime == 'image/gif')
    $ext= '.gif';
elseif($mime == 'image/x-icon')
    $ext = '.ico';
elseif($mime == 'image/bmp')
    $ext = '.bmp';
else {
    $ext = '.jpg';
}
$name = time().$ext;
$path = public_path("images/$controller");
File::isDirectory($path) or File::makeDirectory($path);
if(property_exists($field, 'size') && !$ext=='.gif') {
    $field->size = explode('*',$field->size);
    if($img->resize($field->size[0], $field->size[1])->save("$path/$name")) {
        $data[$key] = $name;
    } else {
        $data[$key] = null;
    }
} else {
    if($img->save("$path/$name")) {
        $data[$key] = $name;
    } else {
        $data[$key] = null;
    }
}

But, those images lose animation after upload. I don't know what to do. How to not lose animation?

Javascript code:

reader.onload = function(e) {
    var src = e.target.result;
    var name = file.name;
    var type = file.type;
    var img = "<img src='"+src+"' class='img-fluid mx-auto' alt='image'>";
    $('.card_group_'+field+' .previewContainer_'+count+' .file-loading').remove();
    $('.card_group_'+field+' .previewContainer_'+count+' .imagePreview').append(img);
    $('.card_group_'+field+' .previewContainer_'+count+' .card-header').append(name);
    var input = "input[name='"+field+"']";
    var added = $(input).val();
    if(added == '') {
        $(input).val(src);
    } else {
        $(input).val(added+';'+src);
    }
}
reader.readAsDataURL(file);

Solution

  • For now, you can use another function to save when it is a gif, and keep using others from the library.

    if ($file->getClientOriginalExtension() == 'gif') {
        copy($file->getRealPath(), $destination);
    }
    else {
        $image->save($destination);
    }
    
    $width = $image->width();
    $height = $image->height();
    $image->destroy();
    

    Credits to: https://github.com/Intervention/image/issues/176#issuecomment-58863939