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

Php 从远程源下载图像并调整大小,然后保存,php,image-resizing,Php,Image Resizing,你们中有谁知道我可以用一个好的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 = imagecreatefr

你们中有谁知道我可以用一个好的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图像函数的更多信息:


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

$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一侧的额外代码确保保存的图像包含任何和所有透明部分。

如果原始图像不是正方形怎么办?你打算裁剪它、缩放它还是做其他事情?如果原始图像小于120x120怎么办?你打算放大它吗?在一个更“回答”的注释中,你应该能够自己快速而简单地编写此代码:使用
file\u get\u content
函数和图像的url将图像的内容放大到一个变量中,然后使用两个GD函数来放大它,最后,
file\u put\u contents
函数保存结果。原始值永远不会小于120x120,但可能需要缩放