How to crop an image without losing its quality?
When I try to crop an image via admin panel, it works with no problems. But when I use the function "add_image_size" or "add_filter", thumbnails loss their quality.
These are the codes I tried.
set_post_thumbnail_size( 212, 159, array( 'center', 'center') );
add_image_size( 'qwqeq', 212, 159, array( 'center', 'center' ) );
add_filter('jpeg_quality', function($arg) { return 100; } );
How can I do this without using any plugin?
Here is a function to scale/crop an image using the php gd library. You can tinker with it to get it to do what you need.
function scaleMyImage($filePath, $newPath, $newSize, $crop = NULL){
$img = imagecreatefromstring(file_get_contents($filePath));
$dst_x = 0;
$dst_y = 0;
$width = imagesx($img);
$height = imagesy($img);
$newWidth = $newSize;
$newHeight = $newSize;
$aspectRatio = $width/$height;
if($width < $height){ //Portrait.
if($crop){
$newWidth = floor($width * ($newSize / $width));
$newHeight = floor($height * ($newSize / $width));
$dst_y = (floor(($newHeight - $newSize)/2)) * -1;
}else{
$newWidth = floor($width * ($newSize / $height));
$newHeight = $newSize;
$dst_x = floor(($newSize - $newWidth)/2);
}
} elseif($width > $height) { //Landscape
if($crop){
$newWidth = floor($width * ($newSize / $height));
$newHeight = floor($height * ($newSize / $height));
$dst_x = (floor(($newWidth - $newSize)/2)) * -1;
}else{
$newWidth = $newSize;
$newHeight = floor($height * ($newSize / $width));
$dst_y = floor(($newSize - $newHeight)/2);
}
}
$finalImage = imagecreatetruecolor($newSize, $newSize);
imagecopyresampled($finalImage, $img, $dst_x, $dst_y, 0, 0, $newWidth, $newHeight, $width, $height);
header('Content-Type: image/jpeg'); //<--Comment out if you want to save to file. Otherwise it will output to your browser.
imagejpeg($finalImage, $newPath, 60); //3rd param is quality. 60 does good job. You can play around.
imagedestroy($img);
imagedestroy($finalImage);
}
$filePath = 'path/to/image.jpg';
$newPath = NULL; //Set to NULL to output to browser. Otherwise set a new filepath to save.
$newSize = 400;
$crop = 1; //Set to NULL if you don't want to crop.
To use:
scaleMyImage($filePath, $newPath, $newSize, 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.