gpt4 book ai didi

php - curl 和调整远程图像的大小

转载 作者:搜寻专家 更新时间:2023-10-31 21:17:46 24 4
gpt4 key购买 nike

我使用此脚本下载远程图像并调整其大小。在调整大小部分出了点问题。这是什么?

<?php
$img[]='http://i.indiafm.com/stills/celebrities/sada/thumb1.jpg';
$img[]='http://i.indiafm.com/stills/celebrities/sada/thumb5.jpg';
foreach($img as $i){
save_image($i);
if(getimagesize(basename($i))){
echo '<h3 style="color: green;">Image ' . basename($i) . ' Downloaded OK</h3>';
}else{
echo '<h3 style="color: red;">Image ' . basename($i) . ' Download Failed</h3>';
}
}

function save_image($img,$fullpath='basename'){
if($fullpath=='basename'){
$fullpath = basename($img);
}
$ch = curl_init ($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);




// now you make an image out of it

$im = imagecreatefromstring($rawdata);

$x=300;
$y=250;

// then you create a second image, with the desired size
// $x and $y are the desired dimensions
$im2 = imagecreatetruecolor($x,$y);


imagecopyresized($im2,$im,0,0,0,0,$x,$y,imagesx($im),imagesy($im));


imagecopyresampled($im2,$im,0,0,0,0,$x,$y,imagesx($im),imagesy($im));

// delete the original image to save resources
imagedestroy($im);



if(file_exists($fullpath)){
unlink($fullpath);
}
$fp = fopen($fullpath,'x');
fwrite($fp, $im2);
fclose($fp);

// remember to free resources
imagedestroy($im2);



}
?>

最佳答案

当我运行它时,PHP 给我以下错误:

Warning: fwrite() expects parameter 2 to be string, resource given ... on line 53

fwrite()将字符串写入文件。你想使用 GD 函数 imagejpeg()将 GD 资源保存到文件中。当我改变时它对我有用

$fp = fopen($fullpath,'x');
fwrite($fp, $im2);
fclose($fp);

imagejpeg($im2, $fullpath);

顺便提一下,如果您使用 cURL 所做的只是抓取文件,您可以简单地使用 file_get_contents()而不是 cURL,假设 PHP 配置为允许 fopen 函数中的完整 URL。 (我相信它是默认设置。)请参阅 the file_get_contents() manual page 上的注释部分。获取更多信息。该函数二进制安全的,因此除了文本文件外,它还可以处理图像。为了使用它,我只是用这一行替换了所有六行 cURL 函数:

$rawdata = file_get_contents($img);

更新:
在回答下面的问题时,您可以在数组键中为它们指定一个新文件名,如下所示:

<?php
$img['img1.jpg']='http://i.indiafm.com/stills/celebrities/sada/thumb1.jpg';
$img['img2.jpg']='http://i.indiafm.com/stills/celebrities/sada/thumb5.jpg';
foreach($img as $newname => $i){
save_image($i, $newname);
if(getimagesize(basename($newname))){

关于php - curl 和调整远程图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4853669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com