I have the image attached below with these specifics:
Width: 3024px
Height: 4032px
The getimagesize() function returns the opposite:
$size = GetimageSize("test.jpg");
echo "image width: " . $size[0] . ", height: " . $size[1];
image width: 4032, height: 3024
How is this possible?
You can try yourself using the image below.
* UPDATE *
Removed image from the post and added a link to zip file (containing the image) because the image works fine after being processed from stack overflow.
Tinyupload ZIP
Screenshot of the result:
Your image is probably being auto-rotated when you view it. Orientation will play a part in getting the height and width the right way around. This code taken from the php documentation will make sure your image is correctly rotated. There are many other examples in the link to choose from.
<?php
$image = imagecreatefromstring(file_get_contents($_FILES['image_upload']['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
switch($exif['Orientation']) {
case 8:
$image = imagerotate($image,90,0);
break;
case 3:
$image = imagerotate($image,180,0);
break;
case 6:
$image = imagerotate($image,-90,0);
break;
}
}
// $image now contains a resource with the image oriented correctly
?>
Function getimagesize() changes width and height in photos that are landscape orientation (horizontal).
You can use this code:
<?php
$img = "test.jpg";
$exif = exif_read_data($img);
if(empty($exif['Orientation'])) {
list($width, $height, $type, $attr) = getimagesize($img);
}else{
list($height, $width, $type, $attr) = getimagesize($img);
}
?>
But it was fixed automatically in PHP7 and above.
The exif orientation tag cannot be fully trusted, as it really depends on the program or device setting the tag that the correct value is used.
This article explains the exif orientation tag better and why it's a mess. http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/
Related
I had the below code that load image from DB. There are more than 600 rows of image has been inserted into the DB. I need the script that can perform these action:
Step 1) Load the image from DB
Step 2) process the image by putting the watermark
Step 3) Output the image to the browser.
I had the below code, that load and show the image. but I don't have any idea how to do the watermark.
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT type,content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$contenttype = #mysql_result($result,0,"type");
$image = #mysql_result($result,0,"content");
header("Content-type: $contenttype");
echo $image;
mysql_close($dbconn);
?>
Please help...
You could ether learn how to manipulate images on your own from php.net or you just get a package like the one below:
http://pear.php.net/package/Image_Tools
(Tools collection of common image manipulations. Available extensions are Blend, Border, Marquee, Mask, Swap, Thumbnail and Watermark.)
How about calling your image the same way you do for the SELECT type, content?
Select the image with an imagepath from your database and then style it so it floats over your information. you could also hardcode the watermark image as it is always the same image you can have repeated. You won't see your information but if you put an opacity on the image, you can see through it:
#img.watermark {
float:left;
opacity:0.1;
z-index:1;
}
This is just one idea on how to do it, but should work quite nicely!
take a look at
imagecopymerge()
from php's graphics librabry, it should do what you're looking for.
http://www.php.net/manual/en/function.imagecopymerge.php
Finally I get the solution, here is the code:
<?php
$dbconn = #mysql_connect($mysql_server,$mysql_manager_id,$mysql_manager_pw) or exit("SERVER Unavailable");
#mysql_select_db($mysql_database,$dbconn) or exit("DB Unavailable");
$sql = "SELECT id, original_name, type, content FROM upload WHERE id=". $_GET["imgid"];
$result = #mysql_query($sql,$dbconn) or exit("QUERY FAILED!");
$fileID = #mysql_result($result,0,"id");
$contenttype = #mysql_result($result,0,"type");
$filename = #mysql_result($result,0,"original_name");
$image = #mysql_result($result,0,"content");
$fileXtension = pathinfo($filename, PATHINFO_EXTENSION);
$finalFileName = $fileID.".".$fileXtension;
// put the file on temporary folder
$filePutPath = "/your/temporary/folder/".$finalFileName;
// put the contents onto file system
file_put_contents($filePutPath, $image);
// get the watermark image
$stamp = imagecreatefrompng('../images/watermark.png');
switch($fileXtension)
{
case 'JPEG':
case 'JPG' :
case 'jpg' :
case 'jpeg':
$im = imagecreatefromjpeg($filePutPath);
break;
case 'gif' :
case 'GIF' :
$im = imagecreatefromgif($filePutPath);
break;
case 'png' :
case 'PNG' :
$im = imagecreatefromgif($filePutPath);
break;
default :
break;
}
list($width, $height) = getimagesize($filePutPath);
// set area for the watermark to be repeated
imagecreatetruecolor($width, $height);
// Set the tile (Combine the source image and the watermark image together)
imagesettile($im, $stamp);
// Make the watermark repeat the area
imagefilledrectangle($im, 0, 0, $width, $height, IMG_COLOR_TILED);
header("Content-type: $contenttype");
// free the memory
imagejpeg($im);
imagedestroy($im);
// delete the file on temporary folder
unlink($filePutPath);
mysql_close($dbconn);
?>
I have a question about the images displaying using a function getImage_w($image,$dst_w), which takes the image URL ($image) and the destination width for this image ($size). Then it re-draws the image changing its height according to the destination width.
That's the function (in libs/image.php file):
function getImage_w($image,$w){
/*** get The extension of the image****/
$ext= strrchr($image, ".");
/***check if the extesion is a jpeg***/
if (strtolower($ext)=='.jpg' || strtolower($ext)=='.jpeg'){
/***send the headers****/
header('Content-type: image/jpeg');
/**get the source image***/
$src_im_jpg=imagecreatefromjpeg($image);
/****get the source image size***/
$size=getimagesize($image);
$src_w=$size[0];
$src_h=$size[1];
/****calculate the distination height based on the destination width****/
$dst_w=$w;
$dst_h=round(($dst_w/$src_w)*$src_h);
$dst_im=imagecreatetruecolor($dst_w,$dst_h);
/**** create a jpeg image with the new dimensions***/
imagecopyresampled($dst_im,$src_im_jpg,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
imagejpeg($dst_im);
}
In a file imagetest.php I have this code portion:
<?php
require 'libs/image.php';
echo '<h1>HELLO WORLD : some html</h1>
<img src="'.displayImg_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200).'">
';
In the past, I used to write the URL with $_GET paramers defining the image. But now , I want to use the function directly in my code.
The problem is that the image is displaying correctly, but the Hello World HTML code is not translated by the browser (I know that the header are already sent by the first code) But I want to know how to display the image correctly without affecting the html code. and also without using get parameters that change the URL of the image to this undesired form :
libs/image.php?image=http://www.example.com/image&width=200
After my earlier, totally wrong answer, I hope to make up for it with this. Try this code:
<?php
function getImage_w($image,$w){
// Get the extension of the file
$file = explode('.',basename($image));
$ext = array_pop($file);
// These operations are the same regardless of file-type
$size = getimagesize($image);
$src_w = $size[0];
$src_h = $size[1];
$dst_w = $w;
$dst_h = round(($dst_w/$src_w)*$src_h);
$dst_im = imagecreatetruecolor($dst_w,$dst_h);
// These operations are file-type specific
switch (strtolower($ext)) {
case 'jpg': case 'jpeg':
$ctype = 'image/jpeg';;
$src_im = imagecreatefromjpeg($image);
$outfunc = 'imagejpeg';
break;
case 'png':
$ctype = 'image/png';;
$src_im = imagecreatefrompng($image);
$outfunc = 'imagepng';
break;
case 'gif':
$ctype = 'image/gif';;
$src_im = imagecreatefromgif($image);
$outfunc = 'imagegif';
break;
}
// Do the resample
imagecopyresampled($dst_im,$src_im,0,0,0,0,$dst_w,$dst_h,$src_w,$src_h);
// Get the image data into a base64_encoded string
ob_start();
$outfunc($dst_im);
$imgdata = base64_encode(ob_get_contents()); // Don't use ob_get_clean() in case we're ever running on some ancient PHP build
ob_end_clean();
// Return the data so it can be used inline in HTML
return "data:$ctype;base64,$imgdata";
}
echo '<h1>HELLO WORLD : some html</h1>
<img src="'.getImage_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200).'" />
';
?>
This basically is not possible. The webbrowser requests the HTML page and expects HTML. Or it requests an image and expects an image. You cannot mix both in one request, just because only one Content-Type can be valid.
However, you can embed the image in HTML using data URI:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4/8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Be aware that the base64 encoding is quite ineffective, so make sure you definitly compress your output, if the browser supports it, using for example gzip.
So for you it likely looks like the following:
echo '<img src="data:image/jpeg;base64,' . base64_encode(displayImg_w('http://www.sanctius.net/wp-content/uploads/2010/05/Avatar-20.jpg',200)) . '">';
And make sure displayimg_w() does not output a header anymore.
Furthermore, displayimg_w() needs to be adjusted at the end to return the image data as string rather than direct output:
ob_start();
imagejpeg($dst_im);
return ob_get_flush();
I am writing a PHP script using the imagick extension. What I want the script to do is take an image a user uploads, and create a 200x128 thumbnail out of it.
That's not the only thing. Obviously, not all images will fit the aspect ratio of 200x128. So what I want the script to do is fill in gaps with a black background.
Right now, the image resizes, but there is no black background and the size isn't correct. Basically, the image should ALWAYS be 200x128. The resized image will go in the center, and the rest of the contents will be filled with black.
Any ideas?
Here's my code:
function portfolio_image_search_resize($image) {
// Check if imagick is loaded. If not, return false.
if(!extension_loaded('imagick')) { return false; }
// Set the dimensions of the search result thumbnail
$search_thumb_width = 200;
$search_thumb_height = 128;
// Instantiate class. Then, read the image.
$IM = new Imagick();
$IM->readImage($image);
// Obtain image height and width
$image_height = $IM->getImageHeight();
$image_width = $IM->getImageWidth();
// Determine if the picture is portrait or landscape
$orientation = ($image_height > $image_width) ? 'portrait' : 'landscape';
// Set compression and file type
$IM->setImageCompression(Imagick::COMPRESSION_JPEG);
$IM->setImageCompressionQuality(100);
$IM->setResolution(72,72);
$IM->setImageFormat('jpg');
switch($orientation) {
case 'portrait':
// Since the image must maintain its aspect ratio, the rest of the image must appear as black
$IM->setImageBackgroundColor("black");
$IM->scaleImage(0, $search_thumb_height);
$filename = 'user_search_thumbnail.jpg';
// Write the image
if($IM->writeImage($filename) == true) {
return true;
}
else {
return false;
}
break;
case 'landscape':
// The aspect ratio of the image might not match the search result thumbnail (1.5625)
$IM->setImageBackgroundColor("black");
$calc_image_rsz_height = ($image_height / $image_width) * $search_thumb_width;
if($calc_image_rsz_height > $search_thumb_height) {
$IM->scaleImage(0, $search_thumb_height);
}
else {
$IM->scaleImage($search_thumb_width, 0);
}
$filename = 'user_search_thumbnail.jpg';
if($IM->writeImage($filename) == true) {
return true;
}
else {
return false;
}
break;
}
}
I know its old but I found the answer after long trying:
you need to use thumbnailimage
(http://php.net/manual/en/imagick.thumbnailimage.php)
with both $bestfit and $fill as true like so:
$image->thumbnailImage(200, 128,true,true);
exec('convert -define jpeg:size=400x436 big_image.jpg -auto-orient -thumbnail 200x218 -unsharp 0x.5 thumbnail.gif');
You'll need to install imagemagick.
sudo apt-get install imagemagick
Take a look at:
http://www.imagemagick.org/Usage/thumbnails/#creation
It shows further examples and how to pad out the thumbnail with a background color of your choice.
I am new to jQuery but im loving it! ive have a problem i cant get round as of yet.
I am using http://www.zurb.com/playground/ajax_upload
which i have got working using the following upload.php
<?
$time= time();
$uploaddir = 'users/'; //<-- Changed this to my directory for storing images
$uploadfile = $uploaddir.$time.basename($_FILES['userfile']['name']); //<-- IMPORTANT
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo $uploaddir.$time.$_FILES['userfile']['name']; // IMPORTANT
#print_r($_FILES);
} else {
// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
// Otherwise onSubmit event will not be fired
echo "error";
}
?>
i have added the time variable to ensure each image is unique. The problem i have is i want to resize and optimise the image on the fly and i am not sure how to do this.
The resize is the most important featuer i require - for example i would like a max width of 300px for the image that is saved even if it was originally 1000px wide. I need to resize proportionaly ( is that a word? :) )
Any help will be great.
Regards
M
To resize images you need libs like GD
The standard function to do this is GD's imagecopyresampled.
In the example is shown one way to resize and keeping the proportion:
//> MAx
$width = 200;
$height = 200;
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
There is two main image manipulation things in PHP, GD or Imagemagick. Both will be able to do what you need. You will need to configure them on your PHP webserver.
I have a iPhone app that uploads pictures to my server. One major issue I am having is a rotating one.
For some reason if I upload a picture from my iPhone, some pictures will automatically rotate. The one's that do get rotated are the ones in portrait mode. I have no code in my script that rotates the images.
How does a server exactly process tall images? Should I modify my php file to check to rotate it ahead after it automatically rotates? Should I code something in my iPhone app that will check this?
Any help is appreciated!
PS: If you need code, feel free to ask!
Some pictures(jpg) have exif data that tells the position the camera was when the picture was shot.
Take a look at http://www.php.net/manual/en/function.exif-read-data.php#76964
You may rotate the pictures server-side like this
Or a better way is to use this library
https://github.com/Intervention/image
And simply use like this-
$img = Image::make('foo.jpg')->orientate();
More can be found here.
When you take a picture your phone saves any rotation metadata in EXIF headers. When you upload the image to your server, that metadata is still sitting there but it's your job to apply it to the image to rotate it (if you want). In PHP you can use a function called exif_read_data:
function correctImageOrientation($filename)
{
$exif = exif_read_data($filename);
if ($exif && isset($exif['Orientation'])) {
$orientation = $exif['Orientation'];
if ($orientation != 1) {
$img = imagecreatefromjpeg($filename);
$deg = 0;
switch ($orientation) {
case 3:
$deg = 180;
break;
case 6:
$deg = 270;
break;
case 8:
$deg = 90;
break;
}
if ($deg) {
$img = imagerotate($img, $deg, 0);
}
imagejpeg($img, $filename, 95);
}
}
}
To use it simply call the function after you save the file. For more info and an additional PHP solution see the original source.