Cropping Image in PHP

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)

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]" />

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);
?>

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...

  1. 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
  2. Determine the image dimensions using imagesx() and imagesy()
  3. 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);

Somebody implemented a handy class that encapsulates this logic here ~ ImageManipulator.php

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);

PHP image cropping rotates image

Regarding your recent comment:

I just realized that the phone itself has already rotated the image after I took it. How can I rotate recently taken images by my phone so they look normal?

to rotate an image in PHP you can use imagerotate function. So, right after you cropped the image and saved it to the $newImage variable, proceed with those operations:

$imageResource = $newImage->getResource();
$angle = '90'; // in degrees
$fileName = "../file_upload_img/43/" . $random_file_name . $_FILES["Filedata"]["name"];
$rotatedImage = imagerotate($imageResource, $angle);
imagejpeg($rotatedImage, $fileName, 95);


Related Topics



Leave a reply



Submit