从远程源下载图像并调整大小,然后保存


download image from remote source and resize then save

你们知道一个好的php类吗?我可以用它从远程源下载图像,将其重新调整为120x120,并用我选择的文件名保存它?

所以基本上我会在"http://www.site.com/image.jpg"保存到我的web服务器"/images/myChosenName.jpg"为120x120像素。

感谢

你可以试试这个:

<?php    
$img = file_get_contents('http://www.site.com/image.jpg');
$im = imagecreatefromstring($img);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = '120';
$newheight = '120';
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($thumb, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,'/images/myChosenName.jpg'); //save image as jpg
imagedestroy($thumb); 
imagedestroy($im);
?>


有关PHP图像函数的更多信息:http://www.php.net/manual/en/ref.image.php

您可以调整大小以保持图像的比例

$im = imagecreatefromstring($img);
$width_orig = imagesx($im);
$height_orig = imagesy($im);
$width = '800';
$height = '800';
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

如果您想同时对jpgpng文件格式执行此操作,以下是对我的帮助:

$imgUrl = 'http://www.example.com/image.jpg';
// or $imgUrl = 'http://www.example.com/image.png';
$fileInfo = pathinfo($imgUrl);
$img = file_get_contents($imgUrl);
$im = imagecreatefromstring($img);
$originalWidth = imagesx($im);
$originalHeight = imagesy($im);
$resizePercentage = 0.5;
$newWidth = $originalWidth * $resizePercentage;
$newHeight = $originalHeight * $resizePercentage;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
if ($fileInfo['extension'] == 'jpg') {
    imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
    imagejpeg($tmp, '/img/myChosenName.jpg', -1);
}
else if ($fileInfo['extension'] == 'png') {
    $background = imagecolorallocate($tmp , 0, 0, 0);
    imagecolortransparent($tmp, $background);
    imagealphablending($tmp, false);
    imagesavealpha($tmp, true);
    imagecopyresized($tmp, $im, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
    imagepng($tmp, '/img/myChosenName.png');
}
else {
    // This image is neither a jpg or png
}
imagedestroy($tmp);
imagedestroy($im);

png侧的额外代码确保保存的图像包含任何和所有透明部分。