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

13

你们中有人知道一个好的PHP类,可以从远程来源下载图像,并将其重新调整为120x120大小,然后以我选择的文件名保存到我的Web服务器上吗?

基本上,我会在“http://www.site.com/image.jpg”处拥有一张图片,将其保存到我的Web服务器“/images/myChosenName.jpg”,大小为120x120像素。

谢谢。


如果原始图像不是正方形呢?你打算裁剪它、扭曲缩放它或者做其他处理吗?如果原始图像小于120x120呢?你打算将其放大吗? - Aleks G
更专业的说,您应该能够相当快速、简单地编写此代码:使用 file_get_content 函数和图像的 url 以获取图像内容并存储到变量中,然后使用一些 GD 函数进行缩放,最后使用 file_put_contents 函数保存结果。 - Aleks G
原始图像大小可能不小于120x120,但可能需要进行缩放。 - Ivar
3个回答

21

你可以尝试这个:

<?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


1
您可以保持图像的比例进行调整大小。
$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;
}

0
如果你想要同时处理 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 方面的额外代码确保保存的图像包含所有透明部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接