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.
Related
Good day guys,
I inherited some legacy code that reads a BLOB from the database, parses it and returns the jpeg stream to be displayed in the browser. The legacy code used to run on PHP 5.5, it has since been deployed on a PHP 7.1 server where I am running into the issue.
I have made sure that the gd library for php is installed and loaded in Apache, I can verify that it is enabled and working with the php info file. I have also dumped the value from the DB and made sure the blob is a valid image, which it is. For some reason or another I cannot get the function to provide the image.
Here is the code for the function after the data has been retrieved from the DB and stored in $image
$image = imagecreatefromstring($image);
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
header ( 'Content-type:image/jpeg' );
if($originalWidth == $width && $originalHeight == $height)
{
if($thumb && $width >= $originalWidth) echo imageautocrop($image);
else echo imagejpeg($image);
}
else
{
$ratio = $originalHeight/$originalWidth;
$height = $width*$ratio;
$height = round($height);
$new = imagecreatetruecolor($width, $height);
imagecopyresampled($new, $image, 0, 0, 0, 0, $width, $height, imagesx($image),imagesy($image));
imageantialias($new, true);
if($thumb) imageautocrop($image);
else imagejpeg($new, null, $quality);
imagedestroy($new);
}
I have tried using the exact dimensions as well as the cropped dimensions, neither of which work.
I am trying to create a thumbnail of an image. I got the php code from the php.net website, but it returns this error:
Warning: imagejpeg(/Users/michelebrizzi/Sites/htdocs/blogmichele/immagini/ragazza_thumb.jpg): failed to open stream: Permission denied in /Users/michelebrizzi/Sites/htdocs/blogmichele/prova/imagescale.php on line 19
What did I make a mistake?
This is the php code I've used:
<?php
// File and new size
$filename = $_SERVER['DOCUMENT_ROOT'].'/cartella_sito/immagini/image.jpg';
$percent = 0.5;
// Content type
// header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb, $_SERVER['DOCUMENT_ROOT']."/cartella_sito/immagini/image_thumb.jpg", 75);
?>
read error messages again. The error message itself says permission denied.
That is pretty routine - getting permission denied. Check the unix level file permissions and make sure the user under which PHP runs has read access. just to test chmod to 777. Then revert to more restrictive settings. Make sure that the entire path chain can be accessed.
It could also be that PHP does not have the directive/permission to go into that directory. I am forgetting the setting. But there is this thing; that for directories outside htdocs/webroot you need to explicitly permit that. See this - Make XAMPP/Apache serve file outside of htdocs. But it appears that this does not apply, as you are trying to access files inside of htdocs.
Try putting some error handling in:
From my experience there are two options why this won't work
1) The file doesn't exist
<?php
// File and new size
$filename = $_SERVER['DOCUMENT_ROOT'].'/cartella_sito/immagini/image.jpg';
if(!file_exists($filename)) {
die("The file does not exist");
}
$percent = 0.5;
// Content type
// header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb, $_SERVER['DOCUMENT_ROOT']."/cartella_sito/immagini/image_thumb.jpg", 75);
?>
2) You do not have the correct permissions
Assuming you are using a client such as FileZilla, right click on the folder of the image and ensure you at least have read access to the file (by going to Folder Permissions)
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()
Im trying to make code for generate thumbnail from base64_decode from mySQL Database but problem is why it said file is not valid JPEG im sure that source file is pure JPG file format. then I can't solve :(
source file (BASE64_ENCODE):
http://pastebin.com/wFBcd79B
image.php in view/Helper folder code:
<?php
class ImageHelper extends Helper {
var $helpers = array('Html');
var $cacheDir = 'imagecache';
function getfile($i) {
preg_match_all("/data:(.*);base64,/", $i, $temp_imagetype);
$imagetype = $temp_imagetype[1][0];
$image = base64_decode(preg_replace("/data.*base64,/","",$i));
//echo $image;
ob_start();
//header("Content-type: ".$imagetype);
header('Content-Type: image/jpeg');
print($image);
$data = ob_get_clean();
//file_put_contents($this->webroot.'tmp/temp.jpg', 'test' );
file_put_contents(ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp.jpg', $data );
//return ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/temp2.jpg';
//return 'temp2.jpg';
return 'temp.jpg';
//}
}
//source from: http://bakery.cakephp.org/articles/hundleyj/2007/02/16/image-resize-helper and modified for base64_decode
function resize($path, $width, $height, $aspect = true, $htmlAttributes = array(), $return = false) {
$types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type
//$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.$this->themeWeb.IMAGES_URL;
$fullpath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.IMAGES_URL;
$temppath = ROOT.DS.APP_DIR.DS.WEBROOT_DIR.DS.'tmp/';
//$formImage = imagecreatefromstring(base64_decode(preg_replace("/data.*base64,/","",$path)));
//$url = $formImage;
//$path = $this->getfile($path);
$url = $temppath.$path;
//$url = preg_replace("/data.*base64,/","",$path);
//$url = base64_decode($url);
if (!($size = getimagesize($url)))
return; // image doesn't exist
if ($aspect) { // adjust to aspect.
if (($size[1]/$height) > ($size[0]/$width)) // $size[0]:width, [1]:height, [2]:type
$width = ceil(($size[0]/$size[1]) * $height);
else
$height = ceil($width / ($size[0]/$size[1]));
}
$relfile = $this->cacheDir.'/'.$width.'x'.$height.'_'.basename($path); // relative file
$cachefile = $fullpath.$this->cacheDir.DS.$width.'x'.$height.'_'.basename($path); // location on server
if (file_exists($cachefile)) {
$csize = getimagesize($cachefile);
$cached = ($csize[0] == $width && $csize[1] == $height); // image is cached
if (#filemtime($cachefile) < #filemtime($url)) // check if up to date
$cached = false;
} else {
$cached = false;
}
if (!$cached) {
$resize = ($size[0] > $width || $size[1] > $height) || ($size[0] < $width || $size[1] < $height);
} else {
$resize = false;
}
if ($resize) {
$image = call_user_func('imagecreatefrom'.$types[$size[2]], $url);
if (function_exists("imagecreatetruecolor") && ($temp = imagecreatetruecolor ($width, $height))) {
imagecopyresampled ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
} else {
$temp = imagecreate ($width, $height);
imagecopyresized ($temp, $image, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
}
call_user_func("image".$types[$size[2]], $temp, $cachefile);
imagedestroy ($image);
imagedestroy ($temp);
}
return $this->output(sprintf($this->Html->image($relfile,$htmlAttributes)));
}
}
?>
'index.php' in view folder code:
<?php
foreach ($products as $product):
echo $this->Image->resize($this->Image->getfile($product['Product']['image1']), 120, 120, false);
endforeach;
?>
Output is error log:
> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file
> [APP/View/Helper/image.php, line 86]
> Warning (2): imagecreatefromjpeg() [function.imagecreatefromjpeg]:
> '/Users/user/Sites/mycakeapp/app/webroot/tmp/temp.jpg' is not a valid
> JPEG file [APP/View/Helper/image.php, line 86]
> Warning (2): imagecopyresampled() expects parameter 2 to be resource, boolean given
> [APP/View/Helper/image.php, line 88]
> Warning (2): imagedestroy() expects parameter 1 to be resource, boolean given
> [APP/View/Helper/image.php, line 94]
The base64 encoded data you link to is exactly 2¹⁶ (65536) bytes long. That number is just too round to be a coincidence.
Is the database column defined as TEXT? Convert it to something bigger, like MEDIUMTEXT or LONGTEXT.
It would make more sense to store images in the file system. While databases can store arbitrary data like files, there are limitations that make it impractical: A larger amount of data has to be transferred from the database server to the application over a network so there's a performance issue. Huge databases take longer to back up. And you may need to modify database settings:
The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers. You can change the message buffer size by changing the value of the max_allowed_packet variable, but you must do so for both the server and your client program.
http://dev.mysql.com/doc/refman/5.0/en/blob.html
I'm trying to load an image from an external site over which I have no control.
Most of the time it works fine (hundreds of images tested so far).
It's now giving me this error for one particular image:
imagecreatefromstring(): gd-jpeg, libjpeg: recoverable error: Corrupt JPEG data: premature end of data segment
from this line:
$im = #imagecreatefromstring( $imageString );
The advice I'd read so far suggests adding:
ini_set("gd.jpeg_ignore_warning", true);
but that's had no effect and I'm still getting the error. I'm doing the ini_set just before the call. Is that relevant?
I'm really stuck on how to ignore this error and carry on.
The problem was due to my error handling. I'd set up an error handler so my call to
$im = #imagecreatefromstring( $imageString );
wasn't suppressing errors.
By modifying my error handler with:
if (error_reporting() === 0)
{
// This copes with # being used to suppress errors
// continue script execution, skipping standard PHP error handler
return false;
}
I can now correctly suppress selected errors.
I found the info here: http://anvilstudios.co.za/blog/php/how-to-ignore-errors-in-a-custom-php-error-handler/
this can be solve with:
ini_set ('gd.jpeg_ignore_warning', 1);
If you are just showing the image, then I suggest simply reading the contents and display the image as follows:
$img = "http://path/to/image";
$contents = file_get_contents($img);
header("Content-Type: image/jpeg");
print($contents);
If you are wanting to copy the image to your server, you have a few options, two of which are the copy() function or the method used above and then fwrite():
Option 1 - The copy() function, available from PHP 4
$file1 = "http://path/to/file";
$dest = "/path/to/yourserver/lcoation";
$docopy = copy($file1, $dest);
Option 2 - Using file_get_contents() and fwrite()
$img = "http://path/to/image";
$contents = file_get_contents($img);
$newfile = "path/to/file.ext";
$fhandler = fopen($newfile, 'w+'); //create if not exists, truncate to 0 length
$write = fwrite($fhandler, $contents); //write image data
$close = fclose($fhandler); //close stream
chmod(0755, $newfile); //make publically readable if you want
I hope you find some use in the above
Considering that you want to make a thumbnail and save it, you could implement a handy resize function like the following:
<?php
function resize($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality){
$ext1 = explode(".",trim($sourcefile));
$ext = strtolower(trim(array_slice($sext1,-1)));
switch($ext):
case 'jpg' or 'jpeg':
$img = imagecreatefromjpeg($sourcefile);
break;
case 'gif':
$img = imagecreatefromgif($sourcefile);
break;
case 'png':
$img = imagecreatefrompng($sourcefile);
break;
endswitch;
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
}
else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height );
// Save thumbnail into a file.
switch($ext):
case 'jpg' or 'jpeg':
$makeimg = imagejpeg($tmpimg, $endfile, $quality);
break;
case 'gif':
$makeimg = imagegif($tmpimg, $endfile, $quality);
break;
case 'png':
$makeimg = imagepng($tmpimg, $endfile, $quality);
break;
endswitch;
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
if($makeimg){
chmod($endfile,0755);
return true;
}else{
return false;
}
}
?>
Then, after you've copied the file to your server using one of my methods in my answer above this, you could simply apply the function as follows:
$doresize = resize($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality);
echo ($doresize == true ? "IT WORKED" : "IT FAILED");
This function serves me pretty well. I apply it to 1000's of images a day and it works like a charm.