Crop image in PHP
If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();
. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.
For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.
Here's a general formula for creating thumbnails:
$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg';
$thumb_width = 200;
$thumb_height = 150;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
Haven't tested this but it should work.
EDIT
Now tested and working.
How can I crop an image properly with php?
Finally, I got the solution of my problem. I had to put the same value of dst_w
and src_w
. The same to dst_h
and src_h
. ¡¡And it works!!
The final solution it is the following:
$b = imagecopyresampled ($dst_image, $src_image, 0, 0, 0, 0, 150, 150, 150, 150);
Crop Image and upload with php
how to crop and upload when click save button? , How to make the php get the cropped image and upload to server?
In the readme, the description of method getCroppedCanvas()
mentions uploading a cropped image:
After then, you can display the canvas as an image directly, or use HTMLCanvasElement.toDataURL to get a Data URL, or use HTMLCanvasElement.toBlob to get a blob and upload it to server with FormData if the browser supports these APIs.1
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
// Use `jQuery.ajax` method
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
So for your example, the button labeled save references cropper but that is only defined inside the callback of the DOM-loaded callback (i.e. window.addEventListener('DOMContentLoaded', function () {
). I would recommend using an event delegate (see example plunker mentioned below) but if you wanted to reference cropper it would need to be declared outside the DOM-loaded callback.
var cropper;
window.addEventListener('DOMContentLoaded', function () {
//assign cropper:
cropper = new Cropper(image, { ...
You can see it in action in this plunker. It utilizes a PHP code that merely takes the uploaded cropped image and returns the base64 encoded version (using base64_encode()).
The PHP code used in the plunker example is listed below:
<?php
$output = array();
if(isset($_FILES) && is_array($_FILES) && count($_FILES)) {
$output['FILES'] = $_FILES;
//this is where the cropped image could be saved on the server
$output['uploaded'] = base64_encode(file_get_contents($_FILES['croppedImage']['tmp_name']));
}
header('Content-Type: application/json');
echo json_encode($output);
Instead of just echoing the base64-encoded version of the file, move_uploaded_file() could be used to upload the file and then return information about the uploaded file (e.g. file ID, path, etc).
move_uploaded_file($_FILES['croppedImage']['tmp_name'], '/path/to/save/cropped/image');
1(https://github.com/fengyuanchen/cropperjs#user-content-getcroppedcanvasoptions)
Crop Image From Center PHP
GD comes bundled with all PHP installations from version 4.3.6 onwards so chances are, you have it.
Here's the steps you need to take...
- Create an image resource using one of the GD
imagecreatefrom*()
functions. The one you use depends on the type of image you're dealing with - Determine the image dimensions using
imagesx()
andimagesy()
- Determine your crop coordinates using the following algorithm and crop using
imagecopy()
Find crop coordinates
$width = imagesx($img);
$height = imagesy($img);
$centreX = round($width / 2);
$centreY = round($height / 2);
$cropWidth = 200;
$cropHeight = 130;
$cropWidthHalf = round($cropWidth / 2); // could hard-code this but I'm keeping it flexible
$cropHeightHalf = round($cropHeight / 2);
$x1 = max(0, $centreX - $cropWidthHalf);
$y1 = max(0, $centreY - $cropHeightHalf);
$x2 = min($width, $centreX + $cropWidthHalf);
$y2 = min($height, $centreY + $cropHeightHalf);
Feel free to use my image manipulation class, it should make some aspects much easier - https://gist.github.com/880506
$im = new ImageManipulator('/path/to/image');
$centreX = round($im->getWidth() / 2);
$centreY = round($im->getHeight() / 2);
$x1 = $centreX - 100;
$y1 = $centreY - 65;
$x2 = $centreX + 100;
$y2 = $centreY + 65;
$im->crop($x1, $y1, $x2, $y2); // takes care of out of boundary conditions automatically
$im->save('/path/to/cropped/image');
Cropping an Image In The Browser Automatically
Say this as max_size.php
<?php header('Content-type: image/jpeg');
function resampleimage($maxsize, $sourcefile, $imgcomp=0){
$g_imgcomp=100-$imgcomp;
if(file_exists($sourcefile)){
$g_is=getimagesize($sourcefile);
if($g_is[0] <= $maxsize && $g_is[1] <= $maxsize){
$new_width=$g_is[0];
$new_height=$g_is[1];
} else {
$w_adjust = ($maxsize / $g_is[0]);
$h_adjust = ($maxsize / $g_is[1]);
if($w_adjust <= $h_adjust){
$new_width=($g_is[0]*$w_adjust);
$new_height=($g_is[1]*$w_adjust);
} else {
$new_width=($g_is[0]*$h_adjust);
$new_height=($g_is[1]*$h_adjust);
}
}
$image_type = strtolower(strrchr($sourcefile, "."));
switch($image_type) {
case '.jpg':
$img_src = imagecreatefromjpeg($sourcefile);
break;
case '.jpeg':
$img_src = imagecreatefromjpeg($sourcefile);
break;
case '.png':
$img_src = imagecreatefrompng($sourcefile);
break;
case '.gif':
$img_src = imagecreatefromgif($sourcefile);
break;
default:
echo("Error Invalid Image Type");
die;
break;
}
$img_dst=imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $new_width, $new_height, $g_is[0], $g_is[1]);
imagejpeg($img_dst);
imagedestroy($img_dst);
return true;
} else {
return false;
}
}
resampleimage($_GET['maxsize'], $_GET['source']);
?>
In the page where you have image
<img id="img" src="max_size.php?maxsize=152&source=[some image path]" />
Crop Uploaded Image To 1:1 Ratio PHP
There is imagecrop()
function in php:
$tmpfile = $_FILES['avatar']['tmp_name'];
switch ($fileext) {
case 'jpg':
case 'jpeg':
$image = imagecreatefromjpeg($tmpfile);
break;
case 'png':
$image = imagecreatefrompng($tmpfile);
break;
default:
die("wtf is this extension??");
}
list($w, $h) = getimagesize($imgfile);
// get width $w and height $h for the image
if ($w < $h) // then keep the width and scale the height
$image = imagecrop($image, array(
"x" => 0,
"y" => ($h - $w) / 2,
"width" => $w,
"height" => $w
));
else if ($h < $w) // then keep the height and scale the width
$image = imagecrop($image, array(
"x" => ($w - $h) / 2,
"y" => 0,
"width" => $h,
"height" => $h
));
I haven't tried this code but I'm quite sure it's right. Try it and tell me if it doesn't work.
UPDATE:
Then you can save the resource $image
with imagejpeg()
or imagepng()
to save the images with the same extensions so you won't have problems with the database:
imagejpeg($image, "/path/to/your/image.jpg");
Crop and Resize image from X and Y Position
You have imagecopy() arguments in wrong order.
The right one is $source_copy_result = imagecopy($source_crop_image, $output, 0, 0, 0, 686, 200, 82);
Cropping image in PHP
You could use imagecopy
to crop a required part of an image. The command goes like this:
imagecopy (
resource $dst_im - the image object ,
resource $src_im - destination image ,
int $dst_x - x coordinate in the destination image (use 0) ,
int $dst_y - y coordinate in the destination image (use 0) ,
int $src_x - x coordinate in the source image you want to crop ,
int $src_y - y coordinate in the source image you want to crop ,
int $src_w - crop width ,
int $src_h - crop height
)
Code from PHP.net - a 80x40 px image is cropped from a source image
<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);
// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);
imagedestroy($dest);
imagedestroy($src);
?>
Related Topics
Woocommerce: Which Hook to Replace Deprecated "Woocommerce_Add_Order_Item_Meta"
The MySQLi Extension Is Missing. Please Check Your PHP Configuration
How to Access a Property With an Invalid Name
Best Way to Do Multiple Constructors in PHP
How to Make a Simple Crawler in PHP
How to Remove Non-Alphanumeric Characters
How to Use Guzzle to Send a Post Request in Json
Is There a Built-In Way to Get All of the Changed/Updated Fields in a Doctrine 2 Entity
How Does the Keyword "Use" Work in PHP and How to Import Classes With It
Difference Between MySQL, MySQLi and Pdo
How to Check If an Array Value Exists
Pdo::Fetchall Vs. Pdo::Fetch in a Loop
Formatting Datetime Object, Respecting Locale::Getdefault()
How to Properly Escape HTML Form Input Default Values in PHP