Hàm compress_png() sau đây sẽ lấy đường dẫn đến tệp PNG và trả về nội dung tệp của tệp nén. Nó làm giảm kích thước tập tin và duy trì tính minh bạch. Đây là cách TinyPNG, Kraken, máy nén. io và các dịch vụ khác như vậy hoạt động, vì vậy bạn có thể xây dựng của riêng mình
Sao chép chức năng và chạy nó như trong các ví dụ dưới đây
Examples
Compress uploaded PNG file
You can compress a PNG file when it's uploaded: (remember to change name in $_FILE[] và $save_to_path)
$read_from_path = $_FILE['file']['tmp_name'];
$save_to_path = "uploads/compressed_file.png";
$compressed_png_content = compress_png($read_from_path);
file_put_contents($save_to_path, $compressed_png_content);
// you don't need move_uploaded_file(). file_put_contents() will do that instead.
Chuyển đổi các tệp PNG một cách nhanh chóng
Bạn tối ưu hóa các tệp PNG đã có trên đĩa
$path_to_uncompressed_file = 'test.png';
$path_to_compressed_file = 'test-small.png';
// this will ensure that $path_to_compressed_file points to compressed file
// and avoid re-compressing if it's been done already
if (!file_exists($path_to_compressed_file)) {
file_put_contents($path_to_compressed_file, compress_png($path_to_uncompressed_file));
}
// and now, for example, you can output the compressed file:
header("Content-Type: image/png");
header('Content-Length: '.filesize($path_to_compressed_file));
readfile($path_to_compressed_file);
Mã trên trang này là Miền công cộng. Hãy sao chép và làm bất cứ điều gì bạn thích
Trở về trang chủ
If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:
What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127).
The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)
i had problems with the example by sandhawk at spies dot com because my png overlay, and the jpeg canvas were using different color depths, so, this function corrects this:
[code] function WatermarkImage($CanvasImage, $WatermarkImage /* MUST BE PHG */, $Opacity=10, $Quality=75) { // create true color canvas image: $canvas_src = imagecreatefromjpeg($CanvasImage); $canvas_w = ImageSX($canvas_src); $canvas_h = ImageSY($canvas_src); $canvas_img = imagecreatetruecolor($canvas_w, $canvas_h); imagecopy($canvas_img, $canvas_src, 0,0,0,0, $canvas_w, $canvas_h); imagedestroy($canvas_src); // no longer needed
// call function with opcity set to 50% and 95% quality WatermarkImage("canvas.jpg", "overlay.png", 50, 95);
[/code]
If you want to resize a png-24 image and preserve the alpha channel you need to set imagealphablending($im_dest, false) on the destination image just after creating it with imagecreatetruecolor() and do a imagesavealpha($im_dest, true) on it before saving it: