i wanted to create a thumbnail with specific custom width & height. The function am using only create a thumbnail with a maximum set width/height.
How do i tweak the below function to give me a defined width/height e.g 50x50, 75x75, 100x100.
$original_photo = "photos/photo.extension";
$newcopy = "photos/thumbnails/photo.extension";
$copy_w = 50;
$copy_h = 50;
$extension = explode('.', 'photo.extension');
$extension = end($extension);
function create_thumbnail($original_photo, $newcopy, $copy_w, $copy_h, $extension) {
list($original_w, $original_h) = getimagesize($original_photo);
$scale_ratio = $original_w / $original_h;
if (($copy_w / $copy_h) > $scale_ratio) {
$copy_w = $copy_h * $scale_ratio;
} else {
$copy_h = $copy_w / $scale_ratio;
}
$img = '';
if ($extension == 'gif') {
$img = imagecreatefromgif($original_photo);
} elseif ($extension == 'png') {
$img = imagecreatefrompng($original_photo);
} else {
$img = imagecreatefromjpeg($original_photo);
}
$true_color = imagecreatetruecolor($copy_w, $copy_h);
imagecopyresampled($true_color, $img, 0, 0, 0, 0, $copy_w, $copy_h, $original_w, $original_h);
if (imagejpeg($true_color, $newcopy, 80) == true) {
return true;
} else {
return false;
}
}
Working with images in PHP/GD can be a pain. There are a lot of edge cases, particularly when transparent PNG/GIFs are manipulated.
If possible, I shamelessly recommend a library I wrote to handle things like this: SimpleImage 3.0
Using SimpleImage, you can achieve the desired effect with the following code:
// Load the image from image.jpg
$image = new \claviska\SimpleImage('image.jpg');
// Create a 50x50 thumbnail, convert to PNG, and write to thumbnail.png
$image->thumbnail(50, 50)->toFile('thumbnail.png', 'image/png');
See this page for more details on how the thumbnail method works and available arguments.
Related
I have a function that uploads files up to 8MB but now I also want to compress or at least rescale larger images, so my output image won't be any bigger than 100-200 KB and 1000x1000px resolution. How can I implement compress and rescale (proportional) in my function?
function uploadFile($file, $file_restrictions = '', $user_id, $sub_folder = '') {
global $path_app;
$new_file_name = generateRandomString(20);
if($sub_folder != '') {
if(!file_exists('media/'.$user_id.'/'.$sub_folder.'/')) {
mkdir('media/'.$user_id.'/'.$sub_folder, 0777);
}
$sub_folder = $sub_folder.'/';
}
else {
$sub_folder = '';
}
$uploadDir = 'media/'.$user_id.'/'.$sub_folder;
$uploadDirO = 'media/'.$user_id.'/'.$sub_folder;
$finalDir = $path_app.'/media/'.$user_id.'/'.$sub_folder;
$fileExt = explode(".", basename($file['name']));
$uploadExt = $fileExt[count($fileExt) - 1];
$uploadName = $new_file_name.'_cache.'.$uploadExt;
$uploadDir = $uploadDir.$uploadName;
$restriction_ok = true;
if(!empty($file_restrictions)) {
if(strpos($file_restrictions, $uploadExt) === false) {
$restriction_ok = false;
}
}
if($restriction_ok == false) {
return '';
}
else {
if(move_uploaded_file($file['tmp_name'], $uploadDir)) {
$image_info = getimagesize($uploadDir);
$image_width = $image_info[0];
$image_height = $image_info[1];
if($file['size'] > 8000000) {
unlink($uploadDir);
return '';
}
else {
$finalUploadName = $new_file_name.'.'.$uploadExt;
rename($uploadDirO.$uploadName, $uploadDirO.$finalUploadName);
return $finalDir.$finalUploadName;
}
}
else {
return '';
}
}
}
For the rescaling I use a function like this:
function dimensions($width,$height,$maxWidth,$maxHeight)
// given maximum dimensions this tries to fill that as best as possible
{
// get new sizes
if ($width > $maxWidth) {
$height = Round($maxWidth*$height/$width);
$width = $maxWidth;
}
if ($height > $maxHeight) {
$width = Round($maxHeight*$width/$height);
$height = $maxHeight;
}
// return array with new size
return array('width' => $width,'height' => $height);
}
The compression is done by a PHP function:
// set limits
$maxWidth = 1000;
$maxHeight = 1000;
// read source
$source = imagecreatefromjpeg($originalImageFile);
// get the possible dimensions of destination and extract
$dims = dimensions(imagesx($source),imagesy($source),$maxWidth,$maxHeight);
// prepare destination
$dest = imagecreatetruecolor($dims['width'],$dims['height']);
// copy in high-quality
imagecopyresampled($dest,$source,0,0,0,0,
$width,$height,imagesx($source),imagesy($source));
// save file
imagejpeg($dest,$destinationImageFile,85);
// clear both copies from memory
imagedestroy($source);
imagedestroy($dest);
You will have to supply $originalImageFile and $destinationImageFile. This stuff comes from a class I use, so I edited it quite a lot, but the basic functionality is there. I left out any error checking, so you still need to add that. Note that the 85 in imagejpeg() denotes the amount of compression.
you can use a simple one line solution through imagemagic library the command will like this
$image="path to image";
$res="option to resize"; i.e 25% small , 50% small or anything else
exec("convert ".$image." -resize ".$res." ".$image);
with this you can rotate resize and many other image customization
Take a look on imagecopyresampled(), There is also a example that how to implement it, For compression take a look on imagejpeg() the third parameter helps to set quality of the image, 100 means (best quality, biggest file) and if you skip the last option then default quality is 75 which is good and compress it.
This below mentioned code is written localhost/uploads/gallery.php file. I am including it in another page so it can be a part of header and footer including all my styling. I did it by include('uploads/gallery.php'); into a div.
Everything is working fine except the header location. When I go to the page where gallery is included which is "localhost/index.php?page=media"(localhost/views/media.php). It does not display thumbnails. I have to refresh the page to see thumbnails. Note: the code is written to display thumbnails when they are generated without refreshing the page.
My concern for asking question is, why i have to refresh page to load thumbnails. My header location is not passing variables correctly. I am a complete noob. please help me with this. Shukriya.
<?php
if(isset($_GET['img'])){
if(file_exists("uploads/{$_GET['img']}")) {
ignore_user_abort(true);
set_time_limit(120);
ini_set('memory_limit', '256M');
$src_image = getimagesize("uploads/{$_GET['img']}");
var_dump($src_image);
if($src_image === false) {
die("Wrong Image");
} # Wrong File Size
// Fixed Thumbnail Size
$thumb_width = 144;
$thumb_height = 144;
$thumb_ratio = round (($thumb_width / $thumb_height), 1);
$src_ratio = round (($src_image[0] / $src_image[1]), 1);
if ($src_ratio > $thumb_ratio) {
//Landescape Image dynamic width...
$new_size = array(($src_image[0] * $thumb_height)/$src_image[1], $thumb_height);
$new_pos = array(($new_size[0] - $thumb_width)/2,0);
} elseif ($src_ratio < $thumb_ratio) {
//PORTRAIT Image dynamic Height.....
$new_size = array($thumb_width, ($src_image[1] * $thumb_width)/$src_image[0]);
$new_pos = array(0, ($new_size[1] - $thumb_height)/2);
} elseif($src_ratio == $thumb_ratio) {
//Square
$new_size = array($thumb_width, $thumb_height);
$new_pos = array(0, 0);
}
if($new_size[0] < 1) $new_size[0] = 1;
if($new_size[1] < 1) $new_size[1] = 1;
$imgz = 'uploads/thumbs/'.$_GET['img'];
//GETTING Variable for Source image type. to create resample
if($src_image['mime'] === "image/jpeg"){
$src = imagecreatefromjpeg('uploads/'.$_GET['img']);
} elseif($src_image['mime'] === "image/png"){
$src = imagecreatefrompng('uploads/'.$_GET['img']);
} elseif($src_image['mime'] === "image/gif"){
$src = imagecreatefromgif('uploads/'.$_GET['img']);
}
$thumb = imagecreatetruecolor($thumb_width, $thumb_height);
imagecopyresampled($thumb, $src, 0,0, $new_pos[0], $new_pos[1], $new_size[0], $new_size[1], $src_image[0], $src_image[1]);
//GETTING Variable for Destination thumb image type. to create resample
if($src_image['mime'] === "image/jpeg"){
imagejpeg($thumb, $imgz);
} elseif($src_image['mime'] === "image/png"){
imagepng($thumb, $imgz);
} elseif($src_image['mime'] === "image/gif"){
imagegif($thumb, $imgz);
}
header("Location: uploads/thumbs/{$_GET['img']}");
} /* If file exists */ die();
} // ALL SCRIPT ENDED
if(is_dir('uploads/thumbs') === false) {
mkdir('uploads/thumbs', 0744);
} // Check & Create Directory
$images = glob('uploads/'.'*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
foreach($images as $image){
$imgs = 'uploads/thumbs/'.substr($image,8);
$nme = substr($image,8);
if(file_exists("$imgs")){
echo "<img src=\"$imgs\" alt=\"$nme\" class=\"img-thumbnail\" />"; //uploads/{$img} , data-toggle=\"modal\" data-target=\"#myModal\"
} else {
echo "<img src=\"?page=media&img=$nme\" alt=\"$nme\" class=\"img-thumbnail\" />";
}
}
?>
This is the code that uploads users logo's I was wondering if anyone could help me.
I want to be able to allow users to upload .png and .gif files too.
Sorry if this is a simple fix but I am very new to php.
<?
//edit logo
function resize_image ($image) {
$imgsize = getimagesize($image);
//check for gallery type to determine thumbnail size
$size_x = 150;
$ratio = 150 / $imgsize[0];
$size_y = $imgsize[1] * $ratio;
$srcimage = ImageCreateFromjpeg ($image);
$newimage = ImageCreateTrueColor($size_x,$size_y);
//$newimage = imagecreate ($size_x, $size_y);
imagecopyresized ($newimage, $srcimage, 0, 0, 0, 0, $size_x, $size_y,
imagesx($srcimage), imagesy($srcimage));
return $newimage;
}
$myrepairer = new repairer;
//resize and upload image
$file = $_FILES['logo']['tmp_name'];
$file_name = $_FILES['logo']['name'];
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.jpg')) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.jpg');
unlink('logos/'.$_REQUEST['id'].'.jpg');
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.jpg');
}
$resultmessage = '<div align="center" class="GreenText">Logo Updated</div>';
You can just get the file extension and use it instead of '.jpg'.
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
So, it'll be something like:
$ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
//upload the image followed by a db update.
if ($file != 'none') {
if (copy($file,'logos/'.$_REQUEST['id'].'.'.$ext)) {
unlink($file);
}
$myrepairer->updatelogo($_REQUEST['id'],$_REQUEST['id']);
$thumbnail = resize_image('logos/'.$_REQUEST['id'].'.'.$ext);
unlink('logos/'.$_REQUEST['id'].'.'.$ext);
ImageJPEG($thumbnail,'logos/'.$_REQUEST['id'].'.'.$ext);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php resizing image on upload rotates the image when i don't want it to
I have created my first ever upload code and was testing it, the image resizes and uploads fine. The only issue I have is that it rotates.
Here is the code:
$errors = array();
$message = "";
if(isset($_POST["test"])){
$name = rand(1,999999) . $_FILES["uploadfile"]["name"];
$temp_name = $_FILES["uploadfile"]["tmp_name"];
$size = $_FILES["uploadfile"]["size"];
$extension = strtolower(end(explode('.', $_FILES['uploadfile']['name'])));
$path = "testupload/" . $name;
$info = getimagesize($temp_name);
$originalwidth = $info[0];
$originalheight = $info[1];
$mime = $info["mime"];
$acceptedHeight = 750;
$acceptedWidth = 0;
$acceptedMimes = array('image/jpeg','image/png','image/gif');
$acceptedfileSize = 4102314;
$acceptedExtensions = array('jpg','jpeg','gif','png');
echo $size;
// check mimetype
if(!in_array($mime, $acceptedMimes)){$errors[] = "mime type not allowed - The file you have just uploaded was a: " . $extension . " file!";}
if(!$errors){if($size > $acceptedfileSize){$errors[] = "filesize is to big - Your file size of this file is: " . $size;}}
if(!$errors){if(!in_array($extension, $acceptedExtensions)){$errors[] = "File extension not allowed - The file you have just uploaded was a: " . $extension . " file!";}}
if(!$errors){
// create the image from the temp file.
if ($extension === 'png'){
$orig = imagecreatefrompng($temp_name);
}elseif ($extension === 'jpeg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'jpg'){
$orig = imagecreatefromjpeg($temp_name);
}elseif ($extension === 'gif'){
$orig = imagecreatefromgif($temp_name);
}
// work out the new dimensions.
if ($acceptedHeight === 0){
$newWidth = $acceptedWidth;
$newHeight = ($originalheight / $originalwidth) * $acceptedWidth;
}else if ($acceptedWidth === 0){
$newWidth = ($originalwidth / $originalheight) * $acceptedHeight;
$newHeight = $acceptedHeight;
}else{
$newWidth = $acceptedWidth;
$newHeight = $acceptedHeight;
}
$originalwidth = imagesx($orig);
$originalheight = imagesy($orig);
// make ssure they are valid.
if ($newWidth < 1){ $newWidth = 1; }else{ $newWidth = round($newWidth ); }
if ($newHeight < 1){ $newHeight = 1; }else{ $newHeight = round($newHeight); }
// don't bother copying the image if its alreay the right size.
if ($originalwidth!== $newWidth || $originalheight !== $newHeight){
// create a new image and copy the origional on to it at the new size.
$new = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($new, $orig, 0,0,0,0, $newWidth, $newHeight, $originalwidth, $originalheight);
}else{
// phps copy on write means this won't cause any harm.
$new = $orig;
}
// save the image.
if ($extension === 'jpeg' || $extension === 'jpg'){
imagejpeg($new, $path, 100);
}else if ($save_ext === 'gif'){
imagegif($new, $path);
}else{
imagepng($new, $path, round(9 - (100 / (100 / 9))));
}
$message = $path;
Can someone please let me know what is going on?
Check the original image is actually in the orientation you expect. I work with images all day and the majority of the time it's Windows Photo Viewer showing the image in a certain orientation (reading an orientation change in the EXIF) but if you open it up in Photoshop it's different.
I tested your code with two images: one was landscape (width > height), the other was portrait (height > width). The code works.
The problem seems to be what #Tavocado said: newer cameras have a sensor to detect the orientation of the camera when the photo was taken, and they store that info in the photo. Also, newer photo viewing software reads that info back from the photo and rotates it before displaying the image. So you all the time see the image with the right orientation (sky up, earth down). However PHP functions (and the rest of the world) don't use that information and display the image as is was taken. That means that you will have to rotate yourself portrait images.
Just load your images in the browser (drag the file on the address bar) you you will see how the image is really stored in the file, without any automatic rotation.
The problem is that the image has embedded EXIF data, probably from the device that took the photo.
Investigate whether your images have embedded rotation information, using exif_read_data, and then auto-correct the rotation with a function like this.
I was just wondering how I can make thumbnails of images stored in hdd and use them in an html page, also I need the thumbnails to be able to enlarge (to their original size) if clicked on preferably inside a div tag on the same page, I would appreciate if anyone could put me in the right direction
thanks
You will need the GD extension enabled. The following code will create a thumbnail file in a subdirectory called ~tmb for a JPEG, PNG and GIF file:
$invalid = true;
if ($file != '.' and $file != '..') {
if (filetype($path_abs.$file) == "file") {
$ext = strtolower(substr($file,strrpos($file,'.')+1));
if ($ext == 'jpg' || $ext == 'jpeg') {
$origimg = #imagecreatefromjpeg($path_abs.$file);
} elseif ($ext == 'png') {
$origimg = #imagecreatefrompng($path_abs.$file);
} elseif ($ext == 'gif') {
$origimg = #imagecreatefromgif($path_abs.$file);
}
if ($origimg !== false) {
$nheight = 0;
$nwidth = 0;
$use_orig = false;
if ($width<=160 and $height<160) {
$nwidth = $width;
$nheight = $height;
$use_orig = true;
$invalid = false;
} else {
if ($width>$height and $width>0) {
$nheight = intval((160 / $width) * $height);
$nwidth = 160;
} elseif ($height>0) {
$nwidth = intval((160 / $height) * $width);
$nheight = 160;
} else {
$image = false;
}
if ($nheight > 0 and $nwidth > 0) {
$newimg = imagecreatetruecolor($nwidth, $nheight);
$bgc = imagecolorallocate ($newimg, 238, 238, 238);
imagefilledrectangle ($newimg, 0, 0, $nwidth, $nheight, $bgc);
if (#imagecopyresampled($newimg, $origimg, 0, 0, 0, 0, $nwidth, $nheight, $width, $height)) {
$image = imagejpeg($newimg, $path_abs.'~tmb/'.$file);
$invalid = false;
} elseif (#imagecopyresized($newimg, $origimg, 0, 0, 0, 0, $nwidth, $nheight, $width, $height)) {
$image = imagejpeg($newimg, $path_abs.'~tmb/'.$file);
$invalid = false;
}
}
}
}
}
}
if (!$invalid) {
if ($use_orig) {
echo '<img src="'.$file.'" alt="" />';
} else {
echo '<img src="~tmb/'.$file.'" alt="" />';
}
} else {
echo '<p>Error for file '.$file.'</p>';
}
In the above code, it resizes them to 160x160, though maintaining aspect ratio.
The gd library allows you to manipulate images.
You will find an article to generate thumbnails here.
If you want to allow your users to view the thumbnail and the original size, the best way is to keep the two versions.
And to display either one or the other.
its so simple,if you have any queries mail at karthid#in.com
$ffmpeg = "ffmpeg Installed path"
$flvfile = "source video file with root path"
$png_path " "Destination video file with root path and file type"
exec("$ffmpeg -y -i $flvfile -vframes 1 -ss 00:01:60 -an -vcodec png -f rawvideo -s 110x90 $png_path");
all the best....
You can use the GD library in PHP to load and resize your images to generate the thumbnails
http://us.php.net/manual/en/image.examples.php
Lookup the PECL extension Imagick. It's usually installable with standard package-managers.
http://se2.php.net/Imagick
You can either dynamically create the thumbnails and serve them using .php files (slow) or make a thumbnail-copy that you store on the server (prefered)
the best way I found is to use the phpThumb class (http://phpthumb.sourceforge.net/).
It has everything you need and more, including caching, filters, watermarks and other cool stuff. Just look at the demo page.
maxImageUpload is useful for creating thumbnails, normal image with an original image.
You can use jQuery to enlarge the thumbnail image.
In my experience GD is not very memory-effective for large images, so I strongly encourage you to use Imagick. I`ve written a code snippet for thumbnail generation with php using the Imagick library. You can modify it to save the image instead of echoing it using http://php.net/manual/en/imagick.writeimage.php