imagecreatefrompng: info being sent but not working properly - php

Alright so I haven't coded in a while so I've been piecing together codes. Anyway, I'm making a site where it will send the Post data from the index.php to the boutique.php. the boutique.php page has the imagecreatefrompng on it
When you send the form data from index.php it will select from the mysql database the option you selected on the index, send that, get the link from the database and send the link to the boutique.php.
Now I've gotten it work, when I include the page without putting in the tag it and i echo the the image link tag from the boutique.php page, the link url shows up, so the code itself is being sent properly. BUT it also shows up the gibberish code:
ÿØÿàJFIFÿþ>CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality ÿÛC
and even when I put the page in the the code is broken, but the image link is being sent.
Boutique.php
<?php
header('Content-Type: image/png');
ob_start();
$image_data = ob_get_clean();
session_start();
mysql_connect('localhost', 'user', 'pw')
or die('Could not connect: ' . mysql_error());
mysql_select_db('data') or die('Could not select database');
$GetTanTable = "SELECT * FROM Pants WHERE maincolor='Tan'";
$GetTan = mysql_query($GetTanTable) or die('Query failed: ' . mysql_error());
while ($RowTan = mysql_fetch_array($GetTan, MYSQL_ASSOC))
{
$GetPantsImage = $RowTan['image'];
if(isset($_POST['PTsubmit']) && $RowTan['subcolor'] == $_POST['PTan'])
{
$horizontal = 'right';
$vertical = 'bottom';
$watermark = imagecreatefrompng($GetPantsImage);
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$src = $_GET["src"];
}
}
$image = imagecreatetruecolor(250, 500);
$black = imagecolorallocate($image, 0, 0, 0);
imagecolortransparent($image, $black);
imagealphablending($image, true);
imagesavealpha($image, true);
$horizontal = 'right';
$vertical = 'bottom';
switch ($horizontal) {
default:
$dest_x = $size[0] - 50;
}
switch ($vertical) {
default:
$dest_y = $size[1] - 50;
}
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width,$watermark_height);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
?>
Now even though the code is being sent properly, when I delete all the if, while statements and put a regular http:// code in the $GetPantsImage, it works. So I really don't understand
THE CODE WORKS WHEN: I take the if/while statements out and i put the actual url that is in the datase

Is the file you are trying to process on a remote server or local?
If it's remote then you must specify the full url:
http://sugarbabiesblog.com/images/thumbs/maykhakipants.png
(In your example you omit the http)
If it's local, you want to omit the domain name:
/images/thumbs/maykhakipants.png
Some insights here: I can't open this PNG file with imagecreatefrompng()

Related

Issues having Facebook profile images

I have been searching the answer for my question for hours but I couldn't find an easy way to do it.
I'm building an Android application using Java and PHP to show, update, insert and delete data from my Database tables. I'm using parameters to interact the Java with the PHP.
My application is using the Facebook sdk for the Login, the users can login and create their accounts using the facebook.
I'm getting the E-mail, name and profile image from every user that tries to create an account on my App.
But I'm getting some issues when I try to get the Image profile from the users. I'm receiving the URL like that:
http://graph.facebook.com/ID_FROM_THE_USER/picture?type=large
I could easily get these images only using Java, but I need to save the Image into a specific directory using PHP. I'm following these steps.
Receiving the image URL from the profile.
Passing the Image URL to my PHP file using parameters.
Saving the Image into a new directory on my local computer.
Inserting into my database the name from the Image, and the directory from the folder where the Image is located.
And I'm stuck on the third step because my code can't recognize that I am sending an Image.
My code to receive the Image:
define('DIRECTORY', 'test');
$content = file_get_contents($image); //$image = received Image
$parts = explode('.', $image);
$new_url = rand(0, pow(10, 5)) . '_' . time() . '.' . "jpg";
$small_percent = 0.5;
$thumb_percent = 0.2;
list($width, $height) = getimagesize($image); //Resizing the image
$small_new_width = $width * $small_percent;
$small_new_height = $height * $small_percent;
$thumb_new_width = $width * $thumb_percent;
$thumb_new_height = $height * $thumb_percent;
//Saving to my directory
file_put_contents(DIRECTORY.'/' . $new_url , $content);
resizeImage($image, DIRECTORY.'/small_' . $new_url, $small_new_width, $small_new_height);
resizeImage($image, DIRECTORY.'/thumb_' . $new_url, $thumb_new_width, $thumb_new_height);
Image resize function:
function resizeImage($source, $dest, $new_width, $new_height)
{
list($width, $height) = getimagesize($source);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($source);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, $dest, 100);
}
What I have tried by far:
I read some Questions from three years ago and the solution was that:
$url = 'http://example.com/image.png';
$img = '/my/folder/flower.png';
file_put_contents($img, file_get_contents($url));
But unfortunately is not working anymore.
Thank you.

php Rotating image and resaving

So I have an image uploaded what I'm trying to do is have the user rotate it, receive that value and rotate the image and replace the original with the new image.
So I have a button:
Rotate
In my js file:
$('.rotate').on('click', function(e){
e.preventDefault();
if(rotate < 360)
rotate = rotate +90;
else
rotate = 0;
var id = $(this).data('id');
$('.img-container img').attr('style', '-webkit-transform: rotate(' + rotate + 'deg)');
$.ajax({
type: "POST",
url: "functions/post",
data: { rotate: rotate, id: id }
});
});
and inside "functions/post":
$degrees = $_POST['rotate'];
$postid = $_POST['postid'];
//user the postid to get the imagefilepath from db
$filename = '../img/uploads/' . $post->getimagepath();
// Content type
header('Content-type: image/jpeg');
// Load
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
// Output
imagejpeg($rotate);
list($width, $height) = getimagesize($rotate);
$newImage = imagecreatetruecolor($width, $height);
imagecopyresampled($newImage, $source, 0, 0, 0, 0, $width, $height, imagesx($source), imagesy($source));
imagejpeg($newImage, realpath('../img/uploads/' . $post->getimagepath()));
// Free the memory
imagedestroy($source);
imagedestroy($rotate);
imagedestroy($newImage);
but it doesn't save the rotated file.. :(
this code i got it from searching through so and google but can't seem to make it work for me yet. None of this code is set in stone so anything that needs changing aslong as it makes it work then its all good and greatly appreciated.
You're not saving the rotated image, you're saving the original image over again.
Try this:
$degrees = $_POST['rotate'];
$postid = $_POST['postid'];
//user the postid to get the imagefilepath from db
$filename = '../img/uploads/' . $post->getimagepath();
// Content type
header('Content-type: image/jpeg');
// Load
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
imagejpeg($rotate, realpath('../img/uploads/' . $post->getimagepath()));
// Free the memory
imagedestroy($source);
imagedestroy($rotate);
(not tested) but you get the idea.

Img displayed in binary code with correct header on browser

I build a class of imgResize:
class imgResize
{
public static function resizeAndOutput($img) {
$orginal_img = $img;
$width = 591;
$height = 332;
$new_width = 161;
$new_height = 91;
$edit_img = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($orginal_img);
imagecopyresampled($edit_img, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($edit_img);
}
}
and in html I try to get this on the fly img displayed:
<img class="img_small" src="<?php imgResize::resizeAndOutput($img)">
just getting binary datas like this:
�����JFIF���������>CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality ���C� $.'
How can i solve my problem?
you have to encode your image in a data uri (and embedding the base64 encoded data as a string in your html) and removing that header() line in php,
or create a link to that image, for example http://example.com/?myimage=id and outputting the image as you are doing (as in giving correct headers and echoing the resulting image)
tell me if you need more info or this gives enough insights.
If you output it directly into a src element, it will of course just be binary garbage inside HTML. That's not how <img> elements work. An <img> element's src needs to have a URL pointing to the image. This can be either a URL like img/foo.jpg, or app/some_script_that_outputs_an_image.php, or a Data URI. But not simply binary data. The script that outputs the image would work in this second case, as target of a app/some_script_that_outputs_an_image.php link.
You actually do it right but in the last part you have a problem. You have to save the image and then return the url of the image to the img element.. Try this code:
class imgResize
{
public static function resizeAndOutput($img) {
$orginal_img = $img;
$width = 591;
$height = 332;
$new_width = 161;
$new_height = 91;
$edit_img = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($orginal_img);
imagecopyresampled($edit_img, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
header('Content-Type: image/jpeg');
//Now we have the image lets create a random filename
//Modify this to your needs
$filename = "images/IMG_" . mt_rand(1000,9999) . ".jpg";
//Random sometimes sucks.. Lets see if we already got a file with that name
//And if exists, loop until we get a unique one
while(file_exists($filename)) {
$filename = "images/IMG_" . mt_rand(1000,9999) . ".jpg";
}
//Now let's save the file
imagejpeg($edit_img, $filename);
//And finally return the file url
return $filename;
}
}
If you don't want to save it, you should output it directly to the browser. You don't need any img tags. That's because when using imagejpeg it's like you have directly opened an image file in the browser. (I don't know if I was clear or not. I'm just trying to describe what it really is)
So the php file will be same and you don't need any html. Just call the function. it will do what it is needed:
imgResize::resizeAndOutput($img);
class imgResize
{
public static function resizeAndOutput($img) {
$orginal_img = $img;
$width = 591;
$height = 332;
$new_width = 161;
$new_height = 91;
$edit_img = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($orginal_img);
imagecopyresampled($edit_img, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
ob_start ();
imagejpeg($edit_img);
$image_data = ob_get_contents ();
ob_end_clean ();
return base64_encode($image_data);
}
HTML
<img class="img_small" src="data:image/jpeg;base64,<?php echo imgResize::resizeAndOutput($img)">

Resize and crop image into square with white background - using GD

I've got a script which caches images from an external feed and stores them in a directory on my server when the image is viewed on site.
At the moment it is working great - storing the original image on my server and also creating two additional thumbnails, with their widths re-sized at 300px and 150px.
I'd like to change this slightly so that the following occurs:
Full/Original image is stored on server (as normal)
Both a square 300x300px & 150x150px .jpg thumbnail are created
However, is it possible, so that once the image width/height is resized, the additional canvas width/height is then added to make it completely square? I guess one of the issues here is determining if the image is a 'portrait' or 'landscape' first?
Also, currently I'm getting a black background with transparent PNG images. Is there any way to overcome this and fill the background with white instead?
Thank you very much for any help!! :)
Here is the code which is doing the resizing (imageCache.php):
<?php
function cacheFetch($url,$size,$age)
{
// directory in which to store cached files, must be writable by PHP
$cacheDir = "cache/";
// cache filename constructed from MD5 hash of URL
$filename = $cacheDir.md5($url);
// append size to filename if not 0
if ($size) $filename .= "_".$size;
// default to fetch the file
$fetch = true;
// but if the file exists, don't fetch if it is recent enough
if (file_exists($filename))
{
$fetch = (filemtime($filename) < (time()-$age));
}
// fetch the file if required
if ($fetch)
{
if (substr($url,0,4)=="http")
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
if (strlen($data))
{
$fp = fopen($filename,"w");
fwrite($fp,$data);
fclose($fp);
$error = false;
}
else
{
$error = true;
}
}
else
{
copy($url,$filename);
$error = false;
}
}
// return the filename only if wget did not fail
if (!$error)
{
if ($size)
{
$src = file_get_contents($filename);
$oldImage = imagecreatefromstring($src);
$oldX = imagesx($oldImage);
$oldY = imagesy($oldImage);
if ($oldX && $oldY)
{
$newX = $size;
$xFactor = ($newX / $oldX);
$newY = intval($oldY * $xFactor);
$newImage = imagecreatetruecolor($newX,$newY);
imagecopyresized($newImage, $oldImage, 0,0,0,0, $newX, $newY, $oldX, $oldY);
imagejpeg($newImage,$filename);
}
}
return $filename;
}
else
{
// as an error occured, delete the empty file so it is retried next time
unlink($filename);
// return false
return false;
}
}
require("includes/common.php");
$id = $_GET["id"];
$size = $_GET["size"];
$sql = "SELECT image_url FROM `".$config_databaseTablePrefix."products` WHERE id='".database_safe($id)."'";
if (database_querySelect($sql,$rows))
{
$src = $rows[0]["image_url"];
$src = cacheFetch($src,$size,604800);
$img = file_get_contents($src);
header("Content-Type: image");
print $img;
}
?>
and here is the .htaccess bit with sizes:
RewriteRule ^fullimage/(.*).jpg$ imageCache.php?id=$1&size=0 [L]
RewriteRule ^smallimage/(.*).jpg$ imageCache.php?id=$1&size=150 [L]
RewriteRule ^mediumimage/(.*).jpg$ imageCache.php?id=$1&size=300 [L]
EDIT: Re-worked code:
if ($size)
{
$src = file_get_contents($filename);
$oldImage = imagecreatefromstring($src);
$oldX = imagesx($oldImage);
$oldY = imagesy($oldImage);
if ($oldX && $oldY)
{
$color = imagecolorallocate($newImage, 255,255,255); //The three parameters are R,G,B
imagefilledrectangle ($newImage, 0, 0, $newX, $newY,$color);
$size = max($newX,$newY);
$newImage = imagecreatetruecolor($newX,$newY);
imagecopyresized($newImage, $oldImage, ($size-$newX)/2,($size-$newY)/2,0,0, $newX, $newY, $oldX, $oldY); //Just the coordinates was changed
imagejpeg($newImage,$filename);
Sorry, I will not add my sugestions to your code, because its is too complicated. SO just the hints.
1. How to make resised image square?
Obviously, we must create square of size of bigger dimension of original image. Here I assume the image has already been resized.
$resized = /*We hae resized image downloaded from the site [note1]*/;
$size = max(imagesx($resized), imagesy($resized)); //Make the square so the thumbnail fits in it
$thumbNail = imagecreate($size, $size); //Square.
imagecopy($thumbNail,
($size-imagesx($resized))/2, //Put the image in the middle of the square
($size-imagesy($resized))/2,
0,
0,
imagesx($resized),
imagesy($resized)
);
[note1] Alternativelly, you can just compute dimensions to make $size and copyresize image on the square. This will be faster, but is more complicated to make pseudocode for it.
2. How to change background of new images
This is no real mystery - you just draw rectangle over whole image:
$color = imagecolorallocate($thumbNail, 255,255,255);
imagefilledrectangle ($thumbNail, 0, 0, imagesx($thumbNail), imagesy($thumbNail),$color);
You can even have a transparent background:
$color = imagecolorallocatealpha($thumbNail, 255,255,255,127);
imagealphablending($thumbNail, false); //[note2]
imagefilledrectangle ($thumbNail, 0, 0, imagesx($thumbNail), imagesy($thumbNail),$color);
imagealphablending($thumbNail, true); //If you use it
[note2] Turn off blending, because transparent+black = black again
3. Code related to answer
First the resizing, copying. In the original code, we have the computed new height and width in $newX and $newY. I will use theese as of the new image sizes.
$size = max($newX,$newY);
$newImage = imagecreatetruecolor($size, $size);
imagecopyresized($newImage, $oldImage, ($size-$newX)/2,($size-$newY)/2,0,0, $newX, $newY, $oldX, $oldY); //Just the coordinates was changed
Then he background. Obviously, you should firs set the background, then copy the image. However, I'm separating theese steps so you can see what function does what.
$newImage = imagecreatetruecolor($newX,$newY);
$color = imagecolorallocate($newImage, 255,255,255); //The three parameters are R,G,B
imagefilledrectangle ($newImage, 0, 0, $newX, $newY,$color);

getimagesize - failed to open stream: Connection timed out in

In my php script in am trying to get an image from a URL, resize it, and upload it to my server. The script can be seen at http://getsharp.net/imageupload.php?admin=rene - The script is seen below (there is of course also some other PHP and HTML in it, but this is the part giving me an issue):
$admin = $_REQUEST['admin'];
$url = $_POST['uploadlink'];
if ($_POST['filename']){
$filename = $_POST['filename'].".jpg";
} else {
$urlinfo = parse_url($url);
$filename = basename($urlinfo['path']);
$filenamearray = explode(".", $filename);
$filenamebase = $filenamearray[0];
$filenamebase = substr($filenamebase, 0, 20); // max 20 characters
$filename = $filenamebase.".jpg";
}
// Get new dimensions
list($width, $height) = getimagesize($url);
$new_width = 300;
$ratio = $height/$width;
$new_height = 300*$ratio;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
if(exif_imagetype($url) == IMAGETYPE_GIF){
$image = imagecreatefromgif($url);
}else if(exif_imagetype($url) == IMAGETYPE_JPEG){
$image = imagecreatefromjpeg($url);
}else if(exif_imagetype($url) == IMAGETYPE_PNG){
$image = imagecreatefrompng($url);
}else{
$image = false;
}
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if(is_dir("images/upload/".$admin."/")){
// Output
imagejpeg($image_p, "images/upload/".$admin."/".$filename);
imagedestroy($image_p);
}else{
mkdir("images/upload/".$admin."/");
// Output
imagejpeg($image_p, "images/upload/".$admin."/".$filename);
imagedestroy($image_p);
}
$URL="http://getsharp.net/imageupload.php?admin=".$admin;
header ("Location: $URL");
Everything is working fine, except that when I throw in a new URL it gives me the following error: Warning: getimagesize(http://buffalocomputerconsulting.com/images/computer.jpg): failed to open stream: Connection timed out in.
However, if i throw in the exact same URL right after, there is no problem, and the image is being uploaded. So every time I try a new URL the first time, it gives me the above error. How can this be?
Thanks.
Your DNS resolves too slowly
Your server tries a nonreplying DNS first
Your server tries to connect on IPv6 first
Your uplink is slow as molasses but it has a caching proxy
I am sure there are more. Try your script on another machine and see whether it changes.

Categories