improve quality of PHP GD generated images

前端 未结 2 1070
再見小時候
再見小時候 2021-01-05 07:17

i am going to start building a map generator in PHP using the GD library. i generated some images using the lib but they don\'t have a good quality. I just want to know that

相关标签:
2条回答
  • 2021-01-05 07:38

    The loss of quality is beacause of JPEG Compression (which is alossy compression algorithm).

    If you want best quality use PNG instead of jpeg.

    header('Content-Type: image/png');
    imagepng($canvas);
    

    And for a map generator I would recommend PNG as there are many solid color areas which will be compressed quite a lot by PNG.

    Only think of using JPEG if the size of PNG images is unacceptably large.
    In that case as jeremy said use the quality argument of imagejpeg..

    imagejpeg($canvas, NULL, $quality);
    

    I would experiment with various qualities to find a suitable size quality trade-off. Personally i have found a quality of 90 to be acceptable in most cases, but you can up it to 100 if you want to.

    0 讨论(0)
  • 2021-01-05 08:02

    imagejpeg[docs] takes an argument for image quality. It defaults to 75, but you can increase it up to a maximum of 100. For example:

    imagejpeg($canvas, NULL, 90);
    

    However, for generated graphics with lots of continuous colours and sharp lines, JPEG is probably not the best choice. PNGs are more well-suited to these sorts of images, and will probably give you perfect quality at a smaller size. imagepng[docs] has a few options, but the defaults should be fine:

    header('Content-Type: image/png');
    imagepng($canvas);
    

     

    You're using imagecreate[docs] to make the image in the first place. This creates a "pallet-based" image: one that can only use a limited number of colours. This matches the lower quality of a GIF or an 8-bit PNG, but because you're not using those formats you should use imagecreatetruecolor[docs] instead. So far, your image is very simple and this might not make a difference, but it will matter if you're generating more complicated images.

    If you make these two changes, your images will be sure to have perfect quality.

    0 讨论(0)
提交回复
热议问题