Problem displaying image with imagejpeg in PHP - php

I'm having an issue using a watermarking script I have. Below is the script:
if (isset($_GET['imgid'])) {
include "../mysql_connect.php";
$imgid = $_GET['imgid'];
$query = "SELECT * FROM img_ref WHERE id='$imgid'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$imagesource = "../ajax_uploads/$row[submitter_id]-uploads/$row[filename]";
} else {
$imagesource = "../ajax_uploads/" . $_GET['path'];
}
$info = pathinfo($imagesource);
$filetype = $info['extension'];
if($filetype == "gif") $image = #imagecreatefromgif($imagesource);
if($filetype == "jpg") $image = #imagecreatefromjpeg($imagesource);
if($filetype == "png") $image = #imagecreatefrompng($imagesource);
if (!$image) die();
$watermark = #imagecreatefrompng('../images/watermark.png');
// This is the key. Without ImageAlphaBlending on, the PNG won't render correctly.
imagealphablending($image, true);
$imagewidth = imagesx($image);
$imageheight = imagesy($image);
$watermarkwidth = imagesx($watermark);
$watermarkheight = imagesy($watermark);
$startwidth = (($imagewidth - $watermarkwidth)/2);
$startheight = (($imageheight - $watermarkheight)/2);
imagecopy($image, $watermark, $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);
Now, if I pass a 'path' variable through, everything works fine and the image is displayed correctly as I would imagine. However, when I attempt to pass through an imgid value, and retrieve the path from the database, the image is presented in raw data on the screen - not as an image.
I have tried specifying the headers
header("Content-type: image/jpeg");
However that hasn't helped. It doesn't seem to be an issue with the folder permissions, as if I specify the path name using the reference in the database, it works fine. It seems to be that including that first "if" section seems to break the output, and I'm at a loss why.
Could anyone possibly shed any light on this for me?
Thank you kindly,
Dan
UPDATE
Okay, somehow its started working with having "Header("Content-type: image/jpeg");" placed at the top of the PHP file, so if I go to the file directly and put in the GET id, I get the picture returned - which is good (no idea what changed though).
However I still have an issue in displaying this picture elsewhere it seems. I'm calling the picture using "fancybox", a jquery plugin. When it displays the image, it is still showing the raw data. If I use the path, it displays fine - just for some reason the raw data shows up when using the GET id option. Am still looking into it but thanks for suggestions so far.

It seems using the header
header("Content-type: image/jpeg");
Seemed to work to get it to display as an image - however it did not work with fancybox for some reason. I looked at the API and have sinced forced fancybox to realise it is an image:
$.fancybox({
'href':'processes/process_watermark.php?imgid=' + id,
'type':'image'
});
That makes it display correctly.
Thanks for everyones help - and all the comments reminding me about SQL attacks.

You don't checking fail of mysql_fetch_array maybe query dont result anything?
Maybe path you giving to pathinfo is not correct.
Your debugging script you should have at the top of script error_reporting(E_ALL)
Change $imagesource = "../ajax_uploads/$row[submitter_id]-uploads/$row[filename]"; to $imagesource = "../ajax_uploads/" . $row['submitter_id'] . "-uploads/" . $row['filename'];

Related

imagejpeg shows a blank image for creating captcha

I tried 3 different codes to create a captcha for my php project,but they all showed gibberish html instead of actually executing it.
I tried both imagepng and imagejpeg and even added the header attribute,but instead of working,it shows nothing but a blank image in the middle of the browser page.I looked up all stack overflow questions for this,but none seems to work for me.
When I remove the header attribute it writes gibberish but when I remove it it shows me a blank image.Is there anyone that can help me?
Here's the last code I coded:
<?php
session_Start();
$length = rand(0,56);
$shuffle=str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890");
$text = substr($shuffle,$length,6);
$_SESSION["captcha"] = $text;
$im = imagecreatetruecolor(18,22);
imagecolorallocate($im,255,255,255);
$fontSize = 24;
$rotate = 13;
$xRotate = 50;
$yRotate = 70;
$font = getcwd()."\\public\\fonts\\arial.ttf";
$color = imagecolorallocate($im,255,0,255);
imagettftext($im,$fontSize,$rotate,$xRotate,$yRotate,$color,$font,$text);
header('Content-Type: image/jpeg');
imagejpeg($im);
?>

resize image on the fly using php

I'v searched all day for a function to resize my pictures on the server on the fly, without saving them.The code works, it shows the full size images, now I want to make them smaller.
This is the function:
function resize_image($file, $width, $height) {
if (file_exists($file)){
$image = imagecreatefromjpeg($file);
list($orig_width, $orig_height) = getimagesize($file);
$ratio = $orig_width / $orig_height;
if ($ratio < 1) {
$width = $height * $ratio;
} else {
$height = $width / $ratio;
}
$new_image = imagecreatetruecolor($width, $height);
imagecopyresized($new_image, $image,
0, 0, 0, 0,
$width, $height,
$orig_width, $orig_height);
// header('Content-type: image/jpeg');
imagejpeg($new_image, NULL, 80);
}
}
From what I searched today I need to put the header (Content-type: image/jpeg') for the browser to recognize the output as an image but if I do that it stops the script.
This is the page using it:
<? include('resize.php');
$chapter='test';
$query=$db->prepare("SELECT * FROM `test_db` WHERE `test_db`.`Chapter` LIKE :? ORDER BY `id` ASC LIMIT 0, 6");
$query->bindValue(1, $chapter, PDO::PARAM_STR);
$query->execute();
$rows= $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row){
echo "<li><h2>".$row['Name']."</h2></li>" ;
resize_image("_images/".$row['img_number'].".jpg", 300, 190);
};
?>
You cannot output html and images to the browser in the same script.
You should either:
use a separate script to output the image and call that from the html like (simple example):
<img src="your_script.php?id=XX&size_x=XX&size_y=XX">
save the images to a file and link to that file from your html.
You could also encode the images as base64 strings and use that in your image tags but that would lead to a very large html file unless you are talking about simple buttons.
Don't put your closing tag in PHP. It will output whitespace after the closing tag which will alter the result.
Since when are headers stopping the script?
And yes, the reason why resized files are saved, is (1) you'll probably need them again, (2) the content type makes them an image in stead of text. If you want to resize those 'inline' you'll need two content types, and I guess that won't work that well...
What you could do, is resize and save the file, serve it and delete it. Like a temporary image file. A more direct way doesn't exist, according to me. But if I'm wrong, please point that out in the comments for me. I like to learn new stuff ;)
Edit: okay, EXCEPT when the script only handles the image resizing. Just thinking about that one right now. Sorry :)

PHP GD2 Images not printing

Recently we launched a in store activation that has you take a photo with a Galaxy Tab 2 and then feeds it to our central server. This is Done with Phonegap. On the server we use PHP and GD2 to generate the images. Everything works on the server and the images are created perfectly, the problem comes when we want to print these photos out with a printer. Currently we are using a HITI Photo Printer, but the same issue occurs on our normal in house printer, on the in house printer it does print the photo but its comes out so small no bigger than 4mm X 2mm on the page.
Below is the code I am using for generating the JPEG on the sever with PHP:
//define image name
$image_name = $this->genUID() .'.jpg';
//get image attributes
list($curWidth, $curHeight, $type, $attr) = getimagesize($files['my_picture']['tmp_name']);
//create image in today's directory
$nI = imagecreatefromjpeg($files['my_picture']['tmp_name']);
$nP = imagecreatetruecolor($this->minimum_image_width, $this->minimum_image_height);
$widthResizeRatio = ($this->minimum_image_width / $curWidth);
$newWidth = $this->minimum_image_width;
$newHeight = round(($curHeight * $widthResizeRatio),0);
$offsetX = 0;
$offsetY = 180;
imagecopyresampled($nP, $nI, 0, 0, $offsetX, $offsetY, $newWidth, $newHeight, $curWidth, $curHeight);
imageinterlace($nP, true);
imagejpeg($nP, $this->image_directory .'/'. $this->curDate .'/'. $image_name, 100);
imagedestroy($nI);
imagedestroy($nP);
Your help will be greatly appreciated.
You said all the images on the server are created perfectly...I would test this claim more carefully. If it is indeed true, the issue lies with how you send the images to your printer or how the printer handles the images once it receives them. In either situation I don't think you are going to get much help here.....I could be wrong. GL.

how do i get the filename of my upload?

this is part of an image upload script i made. I decided to name the rename the images i upload to the time i upload.
date_default_timezone_set('UTC');
$mvTime = date("dmy").(date("H")+5).date("is");
$folder = "images/";
$tmp = imagecreatetruecolor($orig_w, $orig_h);
imagejpeg($tmp, $folder.$mvTime.'.jpg', 100);
now when i upload the image, it saves the image like 051112174700.jpg . its the date in dmyHis format. now i am confused how i show a preview of the image. because the time is changing all the time. thats why i cant use $folder.$mvTime.'jpg' in the tag src.
can any body help me how i can get the image ?
you can use session for temporally save image names
date_default_timezone_set('UTC');
$mvTime = date("dmy").(date("H")+5).date("is");
$folder = "images/";
$tmp = imagecreatetruecolor($orig_w, $orig_h);
imagejpeg($tmp, $folder.$mvTime.'.jpg', 100);
$_SESSION['img_temp_name']=$mvTime.'.jpg';
You know the path of the image already - $folder.$mvTime.'jpg'.
It is not clear from your question but if you want to show a preview immediately after uploading then inside PHP you could do the following:
echo '<img src="'.$folder.$mvTime.'jpg" />";
Alternatively, you will need to come up with a naming convention that allows you to find the image you want later, or store information on the images somewhere (such as in a database).
You defined the image location in the mvTime, so use it like this?
date_default_timezone_set('UTC');
$mvTime = date("dmy").(date("H")+5).date("is");
$folder = "images/";
$tmp = imagecreatetruecolor($orig_w, $orig_h);
imagejpeg($tmp, $folder.$mvTime.'.jpg', 100);
echo '<img src="'.$folder.$mvTime.'.jpg" />'; // <---- added this

Code for displaying thumbnail images

I have a simple PHP script that enables users to upload images on a server. I am after some help in displaying these images as thumbnails in an HTMl page and then letting the user click on these thumbnails and then the original picture is displayed in a new page.
Can I use straight HTML for this? Or do I need some combination of javascript or PHP variant?
I know that there are many questions about this on stackoverflow, and I have tried them, but nothing is what I am after.
I would prefferably like the thumbnails be created on the 'fly' rather than me personally having to create each thumbnal when a user uploads an image.
So basically what language should I use to do this? And also can I have some source code if possible?
thanks
Creating thumbnails every time they are requested is a very bad idea - it takes a lot of processing power, which would be easily saved by keeping them around the first time you create them. I would suggest putting the thumbnail creation in the php script that processes the file upload, so that you save the image and its thumbnail to disk at the same time. You can also keep the thumbnail in memory, or wait until the first time it's requested to create it, but either way you cannot re-generate it every time it is requested.
It is possible to use html to change an image's size, by simply setting the width and/or height properties:
<img src='foo.jpg' alt='foo' width='500' height='300'/>
However, this is a bad idea if you aren't certain that the user will later want to view the full-sized image. The reason is that a thumbnail has a smaller filesize than the full image: if the client only wants to view the thumbnail, then you don't want to waste bandwidth (= your money and the client's time) sending them the full image.
As for your interface, you don't need javascript to accomplish that, just html. However, you will need a server-side script to create the thumbnails that your html page links to.
There are plenty of php thumbnail scripts out there.
Either you use a rewriter to still show the original path, but server a php thumbnail version. Or you have to have the url change to something like:
<img src="thumb.php?file=path/to/picture.jpg&size=128" />
Mighty Stuff
phpThumb
Are just such two. Best configured to utilize the cached folder. I use a modified version of the first script at work.
Here's a PHP script you can build appon only works with jpg images.
It will scan through a directory, normalize the image to a decent dimension and also make a thumb on the fly, then on next refresh it wont need to reprocess the image as its already present in the thumbs dir. Hope it helps...
Script placement
Root>
thisscript.php
/images/
someimage.jpg
someimage2.jpg
thisscript.php
<?php
// config section
$path = "./images/";
$thpath = $path."thumbs/";
// end configration
// Open the directory
$do = dir($path);
// now check if the thumb dir is available if not, create it!!
if (!is_dir($thpath)){
mkdir($thpath);
}
$output = '<div>';
while (($file = $do->read()) !== false){
if (is_dir($path.$file)){
continue;
}else{
$info = pathinfo($path.$file);
$fileext = $info['extension'];
if (strtolower($fileext) == 'jpg'){
if (!is_file($thpath.$file)){
//Normalize Super lrg Image to 750x550
thumb_it($path, $file, $path,750,550,99);
//Make Thumb 200x125
thumb_it($path, $file, $thpath,200,125,99);
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}else{
$output .='<p><img src="'.$thpath.$file.'" title="" alt="" /></p>';
}
}
}
}
$output .='</div>';
echo $output;
//Functions
function thumb_it($dirn, $file, $thumbdir,$rwidth,$rheight,$quality){
set_time_limit(0);
$filename = $dirn.$file;
$thfilename = $thumbdir.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $file);
// get the filename and the thumbernail directory
if (is_file($filename)){
// create the thumbernail from the original picture
$im = #ImageCreateFromJPEG($filename);
if($im==false){return false;}
$width = ImageSx($im); // Original picture width is stored
$height = ImageSy($im); // Original picture height is stored
if (($width < $rwidth) && ($height < $rheight)){
$n_height = $height;
$n_width = $width;
}else{
// saveing the aspect ratio
$aspect_x = $width / $rwidth;
$aspect_y = $height / $rheight;
if ($aspect_x > $aspect_y){
$n_width = $rwidth;
$n_height = $height / $aspect_x;
}else{
$n_height = $rheight;
$n_width = $width / $aspect_y;
}
}
$newimage = imagecreatetruecolor($n_width, $n_height);
// resizing the picture
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
// writing to file the thumbnail
if(file_exists($thfilename)){chmod($thfilename, 0777);}
Imagejpeg($newimage, $thfilename, $quality);
imagedestroy($newimage);
imagedestroy($im);
}
}
?>

Categories