调整GD生成的图像大小但失败

时间:2016-02-23 09:14:13

标签: php gd

我有这个代码,它会在屏幕上生成条形码。但它太小,无法打印。所以,我想缩放尺寸,但为什么$thumb图像没有显示在屏幕上?只显示$ image(原始图像)。我在这里想念的是什么?谢谢

<?php
    //-- bunch of codes here --
    //-- then generate image -- 

    // Draw barcode to the screen
    header ('Content-type: image/png');
    imagepng($image);
    imagedestroy($image);

    // Then resize it
    // Get new sizes
    list($width, $height) = getimagesize($image);
    $newwidth = $width * 2;
    $newheight = $height * 2;

    // Resize
    imagecopyresized($thumb, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    // Output and free memory
    header ('Content-type: image/png');
    imagepng($thumb);
    imagedestroy($thumb);
?>

1 个答案:

答案 0 :(得分:2)

虽然没有使用我模拟部件的所有代码 - 但最终结果是一个两倍于原始尺寸的新图像。最主要的不是最初发送标题,而是将结果图像保存到临时文件,然后使用它。

<?php
    //-- bunch of codes here --
    //-- then generate image -- 


    /* You will already have a resource $image, this emulates that $image so you do not need this line */
    $image=imagecreatefrompng( 'c:/wwwroot/images/maintenance.png' );



    /* define name for temp file */
    $tmpimgpath=tempnam( sys_get_temp_dir(), 'img' );

    /* do not send headers here but save as a temp file */
    imagepng( $image, $tmpimgpath );


    // Then resize it, Get new sizes ( using the temp file )
    list( $width, $height ) = getimagesize( $tmpimgpath );
    $newwidth = $width * 2;
    $newheight = $height * 2;

    /* If $thumb is defined outwith the code you posted then you do not need this line either  */
    $thumb=imagecreatetruecolor( $newwidth, $newheight );

    // Resize
    imagecopyresized( $thumb, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );

    // Output and free memory
    header ('Content-type: image/png');
    @imagedestroy( $image );
    @imagepng( $thumb );
    @imagedestroy( $thumb );
    @unlink( $tmpimgpath );
?>