用PHP调整图片大小? [复制]

Posted

技术标签:

【中文标题】用PHP调整图片大小? [复制]【英文标题】:Resizing picture with PHP? [duplicate] 【发布时间】:2014-02-11 22:44:20 【问题描述】:

我需要将图片调整为固定大小。但它不起作用并出现错误,我该怎么办?

在线演示:http://codepad.org/3OrIHfoy

错误:

致命错误:在线调用未定义函数 imagecreatefromjpeg() 58

php

<?php
function thumbnail_box($img, $box_w, $box_h) 
    //create the image, of the required size
    $new = imagecreatetruecolor($box_w, $box_h);
    if($new === false) 
        //creation failed -- probably not enough memory
        return null;
    


    //Fill the image with a light grey color
    //(this will be visible in the padding around the image,
    //if the aspect ratios of the image and the thumbnail do not match)
    //Replace this with any color you want, or comment it out for black.
    //I used grey for testing =)
    $fill = imagecolorallocate($new, 200, 200, 205);
    imagefill($new, 0, 0, $fill);

    //compute resize ratio
    $hratio = $box_h / imagesy($img);
    $wratio = $box_w / imagesx($img);
    $ratio = min($hratio, $wratio);

    //if the source is smaller than the thumbnail size, 
    //don't resize -- add a margin instead
    //(that is, dont magnify images)
    if($ratio > 1.0)
        $ratio = 1.0;

    //compute sizes
    $sy = floor(imagesy($img) * $ratio);
    $sx = floor(imagesx($img) * $ratio);

    //compute margins
    //Using these margins centers the image in the thumbnail.
    //If you always want the image to the top left, 
    //set both of these to 0
    $m_y = floor(($box_h - $sy) / 2);
    $m_x = floor(($box_w - $sx) / 2);

    //Copy the image data, and resample
    //
    //If you want a fast and ugly thumbnail,
    //replace imagecopyresampled with imagecopyresized
    if(!imagecopyresampled($new, $img,
        $m_x, $m_y, //dest x, y (margins)
        0, 0, //src x, y (0,0 means top left)
        $sx, $sy,//dest w, h (resample to this size (computed above)
        imagesx($img), imagesy($img)) //src w, h (the full size of the original)
    ) 
        //copy failed
        imagedestroy($new);
        return null;
    
    //copy successful
    return $new;

$i = imagecreatefromjpeg("http://techstroke.com/wp-content/uploads/2008/12/image2.png");
$thumb = thumbnail_box($i, 210, 150);
imagedestroy($i);

if(is_null($thumb)) 
    /* image creation or copying failed */
    header('HTTP/1.1 500 Internal Server Error');
    exit();

header('Content-Type: image/jpeg');
imagejpeg($thumb);

【问题讨论】:

我喜欢您尝试使用 imagecreatefromjpeg 来加载 PNG。美好的时光。无论哪种方式,您似乎都没有为您的发行版安装 php5-gd 软件包。 【参考方案1】:

那个错误...

Fatal error: Call to undefined function imagecreatefromjpeg() on line 58

imagecreatefromjpeg() 不可调用,因为它不存在。这意味着您的系统上尚未安装 GD 库。

here are the installation notes。你需要他们让一切顺利进行。由于您从 Internet 上获取了该 php 函数,因此一旦您安装了 GD 库,它应该可以正常工作。

【讨论】:

以上是关于用PHP调整图片大小? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

php在上传或之前调整图片大小

PHP获取远程图片并调整图像大小(转)

world文档怎么准确调整图片大小

QT中怎么调整显示图片大小

如何调整图片kb大小

world文档 把文档里的图片变成一样大小