Home > Enterprise >  How to get image from URL, edit on the fly and save
How to get image from URL, edit on the fly and save

Time:03-25

I have problems on editing an image from web.

Main goal is to get an image from a url, add some padding all around and save it.

//get image
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $image_url); //get result from $image_url
$image_raw = curl_exec($ch); //get image
curl_close($ch);
file_put_contents( 'mysavelocation', $image_raw ); //image saved. this is working fine

//add padding
$orig_img = imagecreatefromstring($image_raw); //get raw image from above. Probably this the part that is not working, because in my understanding, $image_raw should be in different format (?).
list($orig_w, $orig_h) = getimagesize($orig_img); //get image size to add padding later.
echo $orig_w.','.$orig_h; //this is empty

$image_w_padding = imagecreatetruecolor( ($orig_w 20), ($orig_h 20) ); // create new image with 10px padding
imagecopyresampled($image_w_padding, $orig_img, 10, 10, 0, 0, ($orig_w 20), ($orig_h 20), $orig_w, $orig_h); //copy original to new with paddings
imagejpeg($image_w_padding, 'mysavelocation2', 84); //save with jpg quality

PS: I am trying several things with image manipulation lately in PHP but I am strill struggling. Any guides? Note to self: I should put a check somewhere.

CodePudding user response:

Here is an example of functional script doing what you want:

<?php

$padding_size = 20; 
$padding_color = 0xff0000;

$url = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Cat_poster_1.jpg/390px-Cat_poster_1.jpg";
$data = file_get_contents($url);

$image = imagecreatefromstring($data);
$width = imagesx($image);
$height = imagesy($image);

$padded_image = imagecreatetruecolor($width   2*$padding_size, $height   2*$padding_size);
imagefill($padded_image, 0, 0, $padding_color);
imagecopy($padded_image, $image, $padding_size, $padding_size, 0, 0, $width, $height);

imagepng($padded_image, 'padded.png');

Outputs:

enter image description here

  • Related