Reputation: 83
I want to crop a part of an image of 100x100px for example from the middle to 20px height and 30px width and then save it in another file all with PHP.
I was reading and testing some code but i think im lost.
I want to do this because later i want to use OCR to get the text from the new img cropped.
Any help would be great!
Here is some code that i found in the documentation of php.net
<?php
// Create image instances
$src = imagecreatefrompng('waka.png');
$dest = "Select somehow /images ";
// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);
// Output and free from memory
header('Content-Type: image/png');
imagepng($dest);
imagedestroy($dest);
imagedestroy($src);
?>
Im just getting some error about the img can't show when i run it in my local server.
I'm not really sure what i need to change to get a new png. Actually i have 2 img waka.png and wuku.png for testing.
Upvotes: 1
Views: 4773
Reputation: 2595
Starting with your code, this one works for me:
<?php
// load your source image
$src = imagecreatefrompng('1.png');
// create an image resource of your expected size 30x20
$dest = imagecreatetruecolor(30, 20);
// Copy the image
imagecopy(
$dest,
$src,
0, // 0x of your destination
0, // 0y of your destination
50, // middle x of your source
50, // middle y of your source
30, // 30px of width
20 // 20px of height
);
// The second parameter should be the path of your destination
imagepng($dest, '2.png');
imagedestroy($dest);
imagedestroy($src);
You should have 2.png being your cropped image.
Upvotes: 3