Miguel Ramirez Miguel Ramirez - 1 year ago 52
PHP Question

Crop an image and then save it in the same directory

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

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


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.

Answer Source

Starting with your code, this one works for me:

// load your source image
$src = imagecreatefrompng('1.png');
// create an image resource of your expected size 30x20
$dest = imagecreatetruecolor(30, 20);
// Copy the image
    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');


You should have 2.png being your cropped image.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download