douzhanshen0657 2015-03-12 15:05
浏览 50

PHP将图像裁剪为方形拇指并显示黑色条纹

I know this subject seems to appear frequently on this site but nobody seems to have the answer to the problem. I do have a script that rezises an image to show it as a thumbnail of size 200x200px. The image is rezized correctly but when you take a look at the output image you can see that the real size of the thumb is the same ratio as the original and a black stripe fills the rest of the space. Any idea to prevent this and make a REAL crop of the image?

foreach( $images as $image ) {
$dn = dirname($image);
$thumbsDir = $dn; // path to the thumbnails destination directory

$imageName = "thumb.jpg"; // returns "cheeta.jpg"
$thumbnail = $thumbsDir."/".$imageName; // thumbnail full path and name, i.e "./gallery/thumbs/cheeta.jpg"
// for each image, get width and height
$imageSize = getimagesize( $image ); // image size 
$imageWidth = $imageSize[0];  // extract image width 
$imageHeight = $imageSize[1]; // extract image height
// set the thumb size
if( $imageHeight > $imageWidth ){
// images is portrait so set thumbnail width to 100px and calculate height keeping aspect ratio
$thumbWidth = 200;
$thumbHeight = floor( $imageHeight * ( 200 / $imageWidth ) );           
$thumbPosition  = "margin-top: -" . floor( ( $thumbHeight - 200 ) / 2 ) . "px; margin-left: 0";
} else {
// image is landscape so set thumbnail height to 100px and calculate width keeping aspect ratio
$thumbHeight = 200;
$thumbWidth = floor( $imageWidth * ( 200 / $imageHeight ) ); 
$thumbPosition  = "margin-top: 0; margin-left: -" . floor( ( $thumbWidth - 200 ) / 2 ) . "px";
} // END else if
// verify if thumbnail exists, otherwise create it
if ( !file_exists( $thumbnail ) ){
$createFromjpeg = imagecreatefromjpeg( $image );
$thumb_temp = imagecreatetruecolor( $thumbWidth, $thumbHeight );
imagecopyresampled( $thumb_temp, $createFromjpeg, 0 - ($thumbWidth - 200) / 2, 00 - ($thumbHeight - 200) / 2, 0, 0, $thumbWidth, $thumbHeight, $imageWidth, $imageHeight );
imagejpeg( $thumb_temp, $thumbnail, 80 );
} // END if()

Thank you for your help!

See linked image as reference http://i.stack.imgur.com/U743p.jpg

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
    • ¥20 关于URL获取的参数,无法执行二选一查询
    • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
    • ¥15 marlin编译错误,如何解决?
    • ¥15 有偿四位数,节约算法和扫描算法
    • ¥15 VUE项目怎么运行,系统打不开
    • ¥50 pointpillars等目标检测算法怎么融合注意力机制
    • ¥20 Vs code Mac系统 PHP Debug调试环境配置
    • ¥60 大一项目课,微信小程序
    • ¥15 求视频摘要youtube和ovp数据集