converting DURING upload before saving on server png/gif to jpg

北慕城南 提交于 2019-12-01 11:05:56

Using GD, and assuming $images is the directory where you store your images (with ending slash), and $name - the file name of the original image:

$destinationPath = $images . basename($name, $ext) . '.jpg';
$source = imagecreatefrompng($images . $name);
imagejpeg($source, $destinationPath, 75);
imagedestroy($source);

Or with Imagick:

$image = new Imagick($images . $name);
$image->writeImage($destinationPath);
$image->destroy();

Use this function to convert the uploaded image

// http://stackoverflow.com/a/1201823/358906
// Quality is a number between 0 (best compression) and 100 (best quality)
function png2jpg($originalFile, $outputFile, $quality) {
    $image = imagecreatefrompng($originalFile);
    imagejpeg($image, $outputFile, $quality);
    imagedestroy($image);
}

Then delete old image with unlink().

Your code will be something like:

// After the upload
png2jpg($the_jpg_file_path, $the_png_file_path, 80);
unlink($the_jpg_file_path);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!