PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

[FIXED] How to get image from URL, edit on the fly and save

 May 06, 2022     curl, image, image-processing, jpeg, php     No comments   

Issue

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.


Solution

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



Answered By - Gregwar
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing