drvpvmz16241016 2011-02-21 17:41
浏览 11
已采纳

使用cURL输出外部图像,但是如何更改图像的宽度?

header('Content-type: image/jpeg');

$url = $_GET['url']; 

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); 

$file = curl_exec($ch); 

curl_close($ch);

echo $file;

Can anyone please tell me how I can change the width of $file to 300px?

  • 写回答

1条回答 默认 最新

  • 啊啊啊小孔 2011-02-21 17:47
    关注

    If the image is heading for a browser inside an <img> tag, then you can get the browser to rescale it by changing the width attribute.

    Otherwise you need to grab the file and rescale it in your PHP code before outputting it.

    You can use imagecopyresampled() to do that, calculating the height. Then outputting the result.

    Example, following on from obtaining the image in to $file from the code above.

    $img = @imagecreatefromstring($file);
    
    if ($img === false) {
        echo $file;
        exit;
    }
    
    $width = imagesx($img);
    $height = imagesy($img);
    
    $newWidth = 300;
    
    $ratio = $newWidth / $width;
    $newHeight = $ratio * $height;
    
    
    $resized = @imagecreatetruecolor($newWidth, $newHeight);
    
    if ($resized === false) {
        echo $file;
        exit;
    }
    
    $quality = 90;
    
    if (@imagecopyresampled($resized, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height)) {
        @imagejpeg($resized, NULL, $quality);
    } else {
        echo $file;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?