你们中有人知道一个好的PHP类,可以从远程来源下载图像,并将其重新调整为120x120大小,然后以我选择的文件名保存到我的Web服务器上吗?
基本上,我会在“http://www.site.com/image.jpg”处拥有一张图片,将其保存到我的Web服务器“/images/myChosenName.jpg”,大小为120x120像素。
谢谢。
你们中有人知道一个好的PHP类,可以从远程来源下载图像,并将其重新调整为120x120大小,然后以我选择的文件名保存到我的Web服务器上吗?
基本上,我会在“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;
}
$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 方面的额外代码确保保存的图像包含所有透明部分。
file_get_content
函数和图像的 url 以获取图像内容并存储到变量中,然后使用一些 GD 函数进行缩放,最后使用file_put_contents
函数保存结果。 - Aleks G