<?php /* 建立縮略圖 */ $file = __DIR__.'/button.png'; $scale = 0.5; // 比例 $image = ImageCreateFromPNG($file); $thumbnail = ImageCreateTrueColor( ImageSX($image) * $scale, ImageSY($image) * $scale ); // 保留透明度 ImageColorTransparent($thumbnail, ImageColorAllocateAlpha($thumbnail, 0, 0, 0, 127) ); ImageAlphaBlending($thumbnail, false); ImageSaveAlpha($thumbnail, true); // 縮小 & 複製 ImageCopyResampled($thumbnail, $image, 0, 0, 0, 0, ImageSX($thumbnail), ImageSY($thumbnail), ImageSX($image), ImageSY($image) ); header('Content-type: image/png'); ImageJpeg($thumbnail); ImageDestroy($image); ImageDestroy($thumbnail);
說明:php
ImageCopyResampled() 函數用於重採樣拷貝部分圖像並調整大小函數
ImageColorAllocateAlpha() 函數用於爲一副圖像分配顏色 + Alphaspa
ImageAlphaBlending() 函數設定圖像的混色模式 blog
<?php /* 建立固定大小的縮略圖 */ $file = __DIR__.'/button.png'; $w = 50; $h = 20; // 圖像 $original = ImageCreateFromPNG($file); $thumbnail = ImageCreateTrueColor($w, $h); // 保留透明設置 ImageColorTransparent($thumbnail, ImageColorAllocateAlpha($thumbnail, 0, 0, 0, 127) ); ImageAlphaBlending($thumbnail, false); ImageSaveAlpha($thumbnail, true); // 縮小 & 複製 $x = ImageSX($original); $y = ImageSY($original); $scale = min($x / $w, $y / $h); ImageCopyResampled($thumbnail, $original, 0, 0, ($x - ($w * $scale)) / 2, ($y - ($h * $scale)) / 2, $w, $h, $w * $scale, $h * $scale ); header('Content-type: image/png'); ImageJpeg($thumbnail); ImageDestroy($image); ImageDestroy($thumbnail);
說明:class
該方法會從圖像的中心成比例地修剪出盡量大的矩形,須要計算原圖和縮略圖寬度和高度之比,找出其中較小的值。file
從圖像中心減去矩形的通常,得出在原圖中的偏移量:($x - ($w * $scale)) / 2 和 ($y - ($h * $scale)) / 2方法
參考:im
<PHP Cookbook>3'rd di