使用PHP调整图像大小,支持PNG、JPG
我正在使用这个类:使用PHP调整图像大小,支持PNG、JPG,php,image,resize,png,Php,Image,Resize,Png,我正在使用这个类: class ImgResizer { function ImgResizer($originalFile = '$newName') { $this -> originalFile = $originalFile; } function resize($newWidth, $targetFile) { if (empty($newWidth) || empty($targetFile)) { return false; }
class ImgResizer {
function ImgResizer($originalFile = '$newName') {
$this -> originalFile = $originalFile;
}
function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
$src = imagecreatefromjpeg($this -> originalFile);
list($width, $height) = getimagesize($this -> originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
imagejpeg($tmp, $targetFile, 95);
}
}
它工作得很好,但在png上失败了,它创建了一个调整大小的黑色图像
有没有办法调整这个类以支持png图像?你可以试试这个。目前它假设图像将始终是jpeg。这将允许您加载jpeg、png或gif。我还没有测试过,但应该可以用
function resize($newWidth, $targetFile, $originalFile) {
$info = getimagesize($originalFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = 'jpg';
break;
case 'image/png':
$image_create_func = 'imagecreatefrompng';
$image_save_func = 'imagepng';
$new_image_ext = 'png';
break;
case 'image/gif':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = 'gif';
break;
default:
throw new Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, "$targetFile.$new_image_ext");
}
function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
$fileHandle = @fopen($this->originalFile, 'r');
//error loading file
if(!$fileHandle) {
return false;
}
$src = imagecreatefromstring(stream_get_contents($fileHandle));
fclose($fileHandle);
//error with loading file as image resource
if(!$src) {
return false;
}
//get image size from $src handle
list($width, $height) = array(imagesx($src), imagesy($src));
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
//allow transparency for pngs
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
if (file_exists($targetFile)) {
unlink($targetFile);
}
//handle different image types.
//imagepng() uses quality 0-9
switch(strtolower(pathinfo($this->originalFile, PATHINFO_EXTENSION))) {
case 'jpg':
case 'jpeg':
imagejpeg($tmp, $targetFile, 95);
break;
case 'png':
imagepng($tmp, $targetFile, 8.5);
break;
case 'gif':
imagegif($tmp, $targetFile);
break;
}
//destroy image resources
imagedestroy($tmp);
imagedestroy($src);
}
我采用了p.Galbraith的版本,修复了错误,并将其更改为按面积调整大小(宽x高)。对于我自己,我想调整太大的图像的大小
function resizeByArea($originalFile,$targetFile){
$newArea = 375000; //a little more than 720 x 480
list($width,$height,$type) = getimagesize($originalFile);
$area = $width * $height;
if($area > $newArea){
if($width > $height){ $big = $width; $small = $height; }
if($width < $height){ $big = $height; $small = $width; }
$ratio = $big / $small;
$newSmall = sqrt(($newArea*$small)/$big);
$newBig = $ratio*$newSmall;
if($width > $height){ $newWidth = round($newBig, 0); $newHeight = round($newSmall, 0); }
if($width < $height){ $newWidth = round($newSmall, 0); $newHeight = round($newBig, 0); }
}
switch ($type) {
case '2':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = '.jpg';
break;
case '3':
$image_create_func = 'imagecreatefrompng';
// $image_save_func = 'imagepng';
// The quality is too high with "imagepng"
// but you need it if you want to allow transparency
$image_save_func = 'imagejpeg';
$new_image_ext = '.png';
break;
case '1':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = '.gif';
break;
default:
throw Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
$tmp = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled( $tmp, $img, 0, 0, 0, 0,$newWidth,$newHeight, $width, $height );
ob_start();
$image_save_func($tmp);
$i = ob_get_clean();
// if file exists, create a new one with "1" at the end
if (file_exists($targetFile.$new_image_ext)){
$targetFile = $targetFile."1".$new_image_ext;
}
else{
$targetFile = $targetFile.$new_image_ext;
}
$fp = fopen ($targetFile,'w');
fwrite ($fp, $i);
fclose ($fp);
unlink($originalFile);
}
函数resizebyrea($originalFile,$targetFile){
$newArea=375000;//略大于720 x 480
列表($width,$height,$type)=getimagesize($originalFile);
$面积=$宽度*$高度;
如果($area>$newArea){
如果($width>$height){$big=$width;$small=$height;}
如果($width<$height){$big=$height;$small=$width;}
$ratio=$big/$small;
$newSmall=sqrt($newArea*$small)/$big);
$newBig=$ratio*$newSmall;
如果($width>$height){$newWidth=round($newBig,0);$newHeight=round($newSmall,0);}
如果($width<$height){$newWidth=round($newSmall,0);$newHeight=round($newBig,0);}
}
交换机($类型){
案例“2”:
$image_create_func='imagecreatefromjpeg';
$image_save_func='imagejpeg';
$new_image_ext='.jpg';
打破
案例“3”:
$image_create_func='imagecreatefrompng';
//$image_save_func='imagepng';
//“imagepng”的质量太高
//但如果你想让透明化,你就需要它
$image_save_func='imagejpeg';
$new_image_ext='.png';
打破
案例“1”:
$image_create_func='imagecreatefromformgif';
$image_save_func='imagegif';
$new_image_ext='.gif';
打破
违约:
抛出异常('未知图像类型');
}
$img=$image\u create\u func($originalFile);
$tmp=imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled($tmp、$img、0、0、0、$newWidth、$newHeight、$width、$height);
ob_start();
$image\u save\u func($tmp);
$i=ob_get_clean();
//如果文件存在,则创建一个新文件,文件末尾为“1”
如果(文件存在($targetFile.$new\u image\u ext)){
$targetFile=$targetFile.“1”。$new\u image\u ext;
}
否则{
$targetFile=$targetFile.$new\u image\u ext;
}
$fp=fopen($targetFile,'w');
fwrite($fp,$i);
fclose($fp);
取消链接($originalFile);
}
如果要允许透明度,请选中以下选项:
我测试了这个功能,效果很好 我已经编写了一个类,它可以做到这一点,而且非常好用。它叫
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200);
$magicianObj -> saveImage('racecar_convertd.png', 100);
它支持读写(包括转换)以下格式
- jpg
- 巴布亚新几内亚
- gif
- 骨形态发生蛋白
- 屏蔽门
// Include PHP Image Magician library
require_once('php_image_magician.php');
// Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// Resize to best fit then crop
$magicianObj -> resizeImage(100, 200, 'crop');
// Save resized image as a PNG
$magicianObj -> saveImage('racecar_small.png');
公认的答案有很多错误,这里是固定的吗
<?php
function resize($newWidth, $targetFile, $originalFile) {
$info = getimagesize($originalFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = 'jpg';
break;
case 'image/png':
$image_create_func = 'imagecreatefrompng';
$image_save_func = 'imagepng';
$new_image_ext = 'png';
break;
case 'image/gif':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = 'gif';
break;
default:
throw Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, "$targetFile.$new_image_ext");
}
$img=$_REQUEST['img'];
$id=$_REQUEST['id'];
// echo $img
resize(120, $_SERVER['DOCUMENT_ROOT'] ."/images/$id",$_SERVER['DOCUMENT_ROOT'] ."/images/$img") ;
?>
试试这个,使用它,您还可以将图像保存到特定路径
function resize($file, $imgpath, $width, $height){
/* Get original image x y*/
list($w, $h) = getimagesize($file['tmp_name']);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* new file name */
$path = $imgpath;
/* read binary data from image file */
$imgString = file_get_contents($file['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
/* Save image */
switch ($file['type']) {
case 'image/jpeg':
imagejpeg($tmp, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
//exit;
break;
}
return $path;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
现在您需要调用此函数,同时将图像保存为
<?php
//$imgpath = "Where you want to save your image";
resize($_FILES["image"], $imgpath, 340, 340);
?>
我知道这是一个非常古老的线程,但我发现PHP内置了imagescale函数,可以完成所需的工作。见文件 用法示例:
$temp = imagecreatefrompng('1.png');
$scaled_image= imagescale ( $temp, 200 , 270);
这里200是宽度,270是大小调整后的图像的高度。这个问题可能会帮助你弄清楚:imagecreatefrompng($filename)我不理解“如果图像是jpg”,在原始的
resize
方法中,$originalFile
只作为jpeg处理大小调整(imagecreatefromjpeg
/imagejpeg
).我试图将resize()函数替换为您的函数,但它没有生成任何图像;S@Sharpless512进行了编辑,将break
语句放在switch/case
语句的适当位置。谢谢,我没听清楚。(双关语不是有意的)您介意将其重新编写为resize函数吗?它是函数的内容,所以你只需要用相同的函数标记来包装它。但我在上面为你做了。嗨!我刚刚测试了这个,它给了我一个错误,它抛出未知异常。。。知道为什么吗?(问题是,在swich中,它输入默认值,因此不能很好地重新识别mime吗?@tonimichecaubet不确定您是否尝试打印$info以查看返回的mime类型?效果很好,但在指定保存图像的位置时,包含$new\u image\u ext是没有意义的。此调整大小功能的预期输入是resize(100,“newfile.png”、“oldfile.png”)
。另外,抛出异常
应该是抛出新异常
。编辑问题以反映这一点。很有趣!将对其进行一些测试并让您知道。谢谢!您的库是否能够自动根据宽度确定高度大小?如果我想将总图片质量降低50%,而不是作为一个固定数量来保持,该怎么办光电倍率?