PHP Image Change to Silhouette - php

I'm displaying an image where the URL is kept in the database, now i want to display it completely black if a condition isn't met
The URL
$url = '/images/'.$row['sprite'].'.png';
its then displayed in a normal image tag
What i want is if $row['normal'] == 0 then black the image, making it a silhouette, otherwise display the normal image
After some searching I've found about imagefilter but am not sure how to apply it, as the examples i've found don't show how to apply it when there is other content on the page
Or would it be better to make the silhouettes in photoshop, given that there is over 800 of them, though only a maximum of two on the page

Firstly you need to load GD Image Library to your server.
Define your image path and create an image object by using imagecreatefrompng if your image types are different choose correct one.
$image_path = $_SERVER['DOCUMENT_ROOT']."/assets/img/horse1.png";
$image_obj = imagecreatefrompng($image_path);
Now, we need to apply a filter, if your conditions provided. Using the imagefilter function to apply any filter to your image. In this example IMG_FILTER_GRAYSCALE is fair enough or you can change it by using the manual of function.
if($row['normal'] == 0) {
$op_result = imagefilter($image_obj,IMG_FILTER_GRAYSCALE);
}
Finally, we need save the image to server using by imagepng function.
imagepng($image_obj,$_SERVER['DOCUMENT_ROOT']."/assets/img/horse1_black.png");
Check the full code below beacuse I strongly suggest that, you shouldn't create black image for every single user. If your image is already exist in your server just show it without any creation.
$image_path = $_SERVER['DOCUMENT_ROOT']."/assets/img/horse.png";
$black_image_path = $_SERVER['DOCUMENT_ROOT']."/assets/img/horse_black.png";
if($row['normal'] == 0) {
if(file_exists($black_image_path)){
return $black_image_path; //if your black image is already exist just return and use it.
}
else {
$image_obj = imagecreatefrompng($image_path); //create a image object from a path
$op_result = imagefilter($image_obj,IMG_FILTER_GRAYSCALE); //applying grayscale filter to your image object.
if($op_result) {
imagepng($image_obj,$black_image_path); //save the image to defined path.
return $black_image_path;
}
else {
return "Error Occured.";
}
}
}

Related

How to display an image created by imagick php in html view?

I am using phalcon php framework. I have a blog in my application where a user can submit an image attached to his blog post, and it is displayed when viewing the post. I want to display this image on the index page of the blog where each post is listed, however, i want it to be a thumbnail to reduce its size. I was able to use imagick to save a thumbnail at a directory and load the thumbnail from there, however, i need to avoid saving the thumbnail and generate the thumbnails every time just to display them.
Here is the code I used to create the image with imagick
public function thumbnail($img)
{
$maxsize = 100;
$image = new Imagick($img);
// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}
// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage($uploaddir.'/thumbs/'. basename($_FILES['photo']['name']));
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();
}
I tried just to remove the last two lines where the image is saved and then the imagick object is destroyed, but couldn't go on to display the image in the index view.
Step 1 - Use the buffer.
Step 2 - Unlink the already saved image after you get its base64 code.
For example consider the following code snippet:
$im = new Imagick();
$im->setResolution(300,300);
$im->readimage('path_to_the_file.pdf');
$im->setImageFormat('jpeg');
$im->writeImages('file_name_to_save.jpg', false);
$im->clear();
$im->destroy();
$dest = imagecreatefromjpeg ('file_name_to_save.jpg');
//Step 1
ob_start();
imagejpeg($dest);
$image_data = ob_get_clean();
imagedestroy($dest);
$img_source = base64_encode($image_data);
//Step 2
unlink('file_name_to_save.jpg');
Now in the $img_source variable you have the base64 of the image that you can use it like this:
'<img src="data:image/jpg;base64,'.$img_source.'" style="max-width: 100%; max-height:100%;" />';
I'm using something similar to this:
public function thumbAction() {
// Generate thumb from image & save it on disk
$image = $this->thumbnail(); // well can be anything that return Imagick
$this->response->setHeader('Content-Type', 'image/jpg');
echo $image;
}
Anyway in above example you don't need to save the image but only echo created thumb to the user.
Also I'm storing an image on some path like thumbs/a/image.jpg. I've configured nginx to check for existing file and if file does not exists it calls Phalcon script.
In Phalcon app I have a route that points to any /thumbs* path to above action. On first call the image is saved on the path thumbs/a/ so on the next call Nginx server returns that image instead of calling PHP.

Determine extension type using image stream

I am developing an API system for my uploading service (in PHP). At the current moment I support the option to send image data as binary data from file_get_contents, fread, etc, or by encoding it with 64 based system. I am attempting to determine the extension type of the image being uploaded to my service from this binary/base64 data. If it is base64 then I decode it and then process it.
I have the following at the moment:
// We need to figure it out ourselves
if ($type === "")
{
// Let's see if it is a base64 file
$base64 = $this->checkBase64Encoded($file_data);
// We got a 64 based file or binary
$type = $base64 === TRUE ? "base64" : "binary";
}
if ($type == "binary")
{
$im = imagecreatefromstring($file_data);
}
I want to see if it is possible to determine the image extension type for saving the file. What do you guys suggest? I read something about using getimagesize()? Although I am not sure about this. Is there no way to get around temporarily saving the file, processing it, and then renaming it?
I also planned to use this to test that the image was a valid image before i checked for extension but I wasn't exactly sure how to use the getimagesize() function:
try
{
// Get the width and height from the uploaded image
list($width, $height) = getimagesize($file['tmp_name']); // I'm not sure what to put here instead of $file['tmp_name']
}
catch (ErrorException $e)
{
// Ignore read errors
}
if (empty($width) OR empty($height))
{
// Cannot get image size, cannot validate
return FALSE;
}
Please feel free to ask for any clarifications if I was unclear. Thanks so much :)
You're looking for the fileinfo functions, particularly finfo_buffer().

Create image from url: multiple problems

<?php
if(isset($_GET['img']) && is_numeric($_GET['img'])){
$img = $_GET['img'];
$imgarray = array (
'1' => 'http://www.path/to/image1.png',
'2' => 'http://www.path/to/image2.png',
'3' => 'http://www.path/to/image3.png'
);
$src = $imgarray[$img];
header('Content-type: image/png');
echo file_get_contents($src);
}
else
{
header('Content-type: image/png');
echo 'Image could not be loaded';
}
?>
Hello again stackoverflow!
Im having multiple problems.
1: When the $_GET['img'] is set and its numeric, the image will be displayed right, but i want to add text in the upper-right corner of the image... How can i do that? I've looked through multiple GD tutorials and examples but i can't find my answer.
2: When $_GET['img'] isn't set i want to display the text: Image could not be loaded. How cna i do that? Because this doesn't seem to work...
Greetings
What you'll have to do is use GD. Load up the requested image into PHP with imagecreatefrompng(), since you have listed pngs in your array, you'd have to use imagecreatefromjpeg() or whatever depending on their format. Then use one of the text writers like imagestring() to write the text to the location in the image resource returned by imagecreatefrompng(), then return the image resource to the browser.
Can also use one of the functions that uses an external font, like imagettftext(), but would need to have the appropriate font to use on the server.
For the error, if you want it to be an image, you'll need to use imagecreatetruecolor() to make a new image, then use imagecolorallocate() to assign a color palette to it, then use imagestring() to write the error message to the image and return it. Of course, probably be easier just to make an error image in GIMP or something and return it, rather than going through the trouble of generating a new error image each time.
Just remove the line that says header('Content-type: image/png'); in your else{} block
That will do the trick. At the moment your are telling the user's browser to treat that text as an image, of course that can't work. If you want an image with the text "Image could not be loaded", it's more complicated than that...

Generate image with Drupal imagecache before using imagecache_create_path & getimagesize

I'm using imagecache_create_path() and getimagesize() to get the path of a imagecache-generated image and its dimensions. However, if it's the first time we access the page that image doesn't exist yet and imagecache_create_path doesn't generate it either.
Here's the code:
// we get the image path from a preset (always return the path even if the file doesn't exist)
$small_image_path = imagecache_create_path('gallery_image_small', $image["filepath"]);
// I get the image dimensions (only if the file exists already)
$data_small = list($width, $height, $type, $image_attributes) = #getimagesize($small_image_path);
Is there any API method to get the path AND generate the file? In other words, can I generate the image (using a preset) from PHP without showing it in the browser?
Thank you in advance
Check the imagecache_build_derivative() function and its usage in imagecache.module. For your case, it should work roughly like so:
$presetname = 'gallery_image_small';
$preset = imagecache_preset_by_name($presetname);
$src = $image["filepath"];
$dst = imagecache_create_path($presetname, $src);
// Ensure existing derivative or try to create it on the fly
if (file_exists($dst) || imagecache_build_derivative($preset['actions'], $src, $dst)) {
// Do what you need to do with the image
}
(NOTE: untested code, beware of typos and other errors/oversights)

Saving a transparent image from a URL in PHP

I am trying to build a class that does many photo operations, one method will upload images from a user but I am also needing to build a method to grab a photo from a URL and run other methods on it just like if it were being uploaded with a POST form from user.
Below is my start of the function for getting image from URL, it works but needs work still. Below the code you can see a image that is the result of this function being ran. Also is the original image to see what it should look like. You can see that this function makes the image have a black background on this transparent image. How can I make it look better like it should look?
$url = 'http://a0.twimg.com/a/1262802780/images/twitter_logo_header.png';
//run our function
savePhotofromURL($url, 'no');
// photo function should grab an photo from a URL
function savePhotofromURL($photo_url, $saveimage = 'yes'){
if(isset($photo_url) && $photo_url != '') {
//get info about photo
$photo_info = getimagesize($photo_url);
$source_width = $photo_info['0'];
$source_height = $photo_info['1'];
$source_type = $photo_info['mime'];
//grab the Photo from URL
$photo = imagecreatefromstring(file_get_contents($photo_url));
if (is_resource($photo) === true){
if($saveimage === 'yes'){
// TO DO: resize image and make the thumbs code would go here if we are saving image:
// TO DO: resize source image if it is wider then 800 pixels
// TO DO: make 1 thumbnail that is 150 pixels wide
}else{
// We are not saving the image show it in the user's browser
// TO DO: we will add in correct photo type soon
header('Content-Type: image/gif');
imagejpeg($photo, null, 100);
imagedestroy($photo);
}
}else{
// not a valid resource, show error
echo 'error getting URL photo from ' .$photo_url;
}
}else{
// url of image was empty
echo 'The URL was not passed into our function';
}
}
The result looks like this
alt text http://img2.pict.com/52/05/1f/2429493/0/screenshot2b181.png
Instead of like this
The following two calls will tell php to use the alpha blending present in the png image:
ImageAlphaBlending($photo, false);
ImageSaveAlpha($photo, true);
Edit:
I see you're outputting the image as a JPEG also. JPEGs don't support transparency, so no matter what you do you will end up with an incorrect background color. Also see this related question: PHP/GD ImageSaveAlpha and ImageAlphaBlending
You need to add better support for image types and by extension their transparency.
Since the image is transparent we can know that its either a GIF or a PNG yet your sending the GIF header while using imagejpeg() - jpegs dont support any kind of transparency. But if its a png you may also have to account for if its alpha trans or index transparency.

Categories