php上传png_php – 如何使用GD调整上传图像并将其转换为PNG

这段代码展示了一个PHP函数,它使用GD库接收不同格式(GIF, JPEG, PNG)的图像,将其调整到指定的最大尺寸,并转换为PNG格式。在调整大小和转换前,函数会检查原始图像的宽高比,以保持其比例。最后,将转换后的PNG图像数据返回为字符串。这个函数适用于需要在数据库中存储PNG头像图像的情况,且在处理大型图像时会临时增加内存限制。
摘要由CSDN通过智能技术生成

我想允许用户以各种格式(至少GIF,JPEG和PNG)上传头像类型的图像,但将其全部保存为PNG数据库BLOB.如果图像超大,像素化,我想在DB插入之前调整它们大小.

使用GD进行调整大小和PNG转换的最佳方式是什么?

编辑:可悲的是,只有GD可用在我需要使用的服务器上,没有ImageMagick.

/*

Resizes an image and converts it to PNG returning the PNG data as a string

*/

function imageToPng($srcFile, $maxSize = 100) {

list($width_orig, $height_orig, $type) = getimagesize($srcFile);

// Get the aspect ratio

$ratio_orig = $width_orig / $height_orig;

$width = $maxSize;

$height = $maxSize;

// resize to height (orig is portrait)

if ($ratio_orig < 1) {

$width = $height * $ratio_orig;

}

// resize to width (orig is landscape)

else {

$height = $width / $ratio_orig;

}

// Temporarily increase the memory limit to allow for larger images

ini_set('memory_limit', '32M');

switch ($type)

{

case IMAGETYPE_GIF:

$image = imagecreatefromgif($srcFile);

break;

case IMAGETYPE_JPEG:

$image = imagecreatefromjpeg($srcFile);

break;

case IMAGETYPE_PNG:

$image = imagecreatefrompng($srcFile);

break;

default:

throw new Exception('Unrecognized image type ' . $type);

}

// create a new blank image

$newImage = imagecreatetruecolor($width, $height);

// Copy the old image to the new image

imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output to a temp file

$destFile = tempnam();

imagepng($newImage, $destFile);

// Free memory

imagedestroy($newImage);

if ( is_file($destFile) ) {

$f = fopen($destFile, 'rb');

$data = fread($f);

fclose($f);

// Remove the tempfile

unlink($destFile);

return $data;

}

throw new Exception('Image conversion failed.');

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值