php – 如何使用GD调整上传图像并将其转换为PNG?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 如何使用GD调整上传图像并将其转换为PNG?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1734字,纯文字阅读大概需要3分钟。
内容图文
![php – 如何使用GD调整上传图像并将其转换为PNG?](/upload/InfoBanner/zyjiaocheng/710/23e2b9b911284ced88120d4b67c2c83b.jpg)
我想允许用户上传各种格式的头像类型图像(至少GIF,JPEG和PNG),但要将它们全部保存为PNG数据库BLOB.如果图像是超大的,按像素,我想在DB插入之前调整它们的大小.
使用GD进行大小调整和PNG转换的最佳方法是什么?
编辑:可悲的是,我需要使用的服务器上只有GD可用,没有ImageMagick.
解决方法:
<?php
/*
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.');
}
内容总结
以上是互联网集市为您收集整理的php – 如何使用GD调整上传图像并将其转换为PNG?全部内容,希望文章能够帮你解决php – 如何使用GD调整上传图像并将其转换为PNG?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。