How can I convert all images to jpg? - php

I have script:
<?php
include('db.php');
session_start();
$session_id = '1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if (strlen($name)) {
list($txt, $ext) = explode(".", $name);
if (in_array($ext, $valid_formats)) {
if ($size < (1024 * 1024)) { // Image size max 1 MB
$actual_image_name = time() . $session_id . "." . $ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if (move_uploaded_file($tmp, $path . $actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/" . $actual_image_name . "' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} else {
echo "Please select image..!";
}
exit;
}
?>
Is possible convert all images (png, gif etc) to jpg with 100% quality? If yes, how? I would like allow to upload png and gif, but this script should convert this files to jpg. Is possible this with PHP?

Try this code: originalImage is the path of... the original image... outputImage is self explaining enough. Quality is a number from 0 to 100 setting the output jpg quality (0 - worst, 100 - best)
function convertImage($originalImage, $outputImage, $quality)
{
// jpg, png, gif or bmp?
$exploded = explode('.',$originalImage);
$ext = $exploded[count($exploded) - 1];
if (preg_match('/jpg|jpeg/i',$ext))
$imageTmp=imagecreatefromjpeg($originalImage);
else if (preg_match('/png/i',$ext))
$imageTmp=imagecreatefrompng($originalImage);
else if (preg_match('/gif/i',$ext))
$imageTmp=imagecreatefromgif($originalImage);
else if (preg_match('/bmp/i',$ext))
$imageTmp=imagecreatefrombmp($originalImage);
else
return 0;
// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);
return 1;
}

Try using Imagick setImageFormat, for me it provides the best image quality
http://php.net/manual/en/imagick.setimageformat.php
$im = new imagick($image);
// convert to png
$im->setImageFormat('png');
//write image on server
$im->writeImage($image .".png");
$im->clear();
$im->destroy();

Davide Berra's answer is great, so I improved the file type detection a little, using exif_imagetype() instead of relying on the file extension:
/**
* Auxiliar function to convert images to JPG
*/
function convertImage($originalImage, $outputImage, $quality) {
switch (exif_imagetype($originalImage)) {
case IMAGETYPE_PNG:
$imageTmp=imagecreatefrompng($originalImage);
break;
case IMAGETYPE_JPEG:
$imageTmp=imagecreatefromjpeg($originalImage);
break;
case IMAGETYPE_GIF:
$imageTmp=imagecreatefromgif($originalImage);
break;
case IMAGETYPE_BMP:
$imageTmp=imagecreatefrombmp($originalImage);
break;
// Defaults to JPG
default:
$imageTmp=imagecreatefromjpeg($originalImage);
break;
}
// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);
return 1;
}
You must have php_exif extension enabled to use this.

A small code to convert image.png to image.jpg at desired image quality:
<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70); // 0 = worst / smaller file, 100 = better / bigger file
imagedestroy($image);
?>

a small fix to davide's answer, the correct function for converting from BMP is "imagecreatefromwbmp" instead of imagecreatefrombmp (missing "w")
also you should consider that png may be transparent, here is a way to fill it with white BG (jpeg can't apply alpha data).
function convertImage($originalImage, $outputImage, $quality){
// jpg, png, gif or bmp?
$exploded = explode('.',$originalImage);
$ext = $exploded[count($exploded) - 1];
if (preg_match('/jpg|jpeg/i',$ext)){$imageTmp=imagecreatefromjpeg($originalImage);}
else if (preg_match('/png/i',$ext)){$imageTmp=imagecreatefrompng($originalImage);}
else if (preg_match('/gif/i',$ext)){$imageTmp=imagecreatefromgif($originalImage);}
else if (preg_match('/bmp/i',$ext)){$imageTmp=imagecreatefromwbmp($originalImage);}
else { return false;}
// quality is a value from 0 (worst) to 100 (best)
imagejpeg($imageTmp, $outputImage, $quality);
imagedestroy($imageTmp);
return true;
}

From PhpTools:
/**
* #param string $source (accepted jpg, gif & png filenames)
* #param string $destination
* #param int $quality [0-100]
* #throws \Exception
*/
public function convertToJpeg($source, $destination, $quality = 100) {
if ($quality < 0 || $quality > 100) {
throw new \Exception("Param 'quality' out of range.");
}
if (!file_exists($source)) {
throw new \Exception("Image file not found.");
}
$ext = pathinfo($source, PATHINFO_EXTENSION);
if (preg_match('/jpg|jpeg/i', $ext)) {
$image = imagecreatefromjpeg($source);
} else if (preg_match('/png/i', $ext)) {
$image = imagecreatefrompng($source);
} else if (preg_match('/gif/i', $ext)) {
$image = imagecreatefromgif($source);
} else {
throw new \Exception("Image isn't recognized.");
}
$result = imagejpeg($image, $destination, $quality);
if (!$result) {
throw new \Exception("Saving to file exception.");
}
imagedestroy($image);
}

Related

Can't upload image with 100% quality

I'm trying to upload image via PHP, but I'm unable to upload an image with 100% quality.
The code I'm actually using
class imaging
{
// Variables
private $img_input;
private $img_output;
private $img_src;
private $format;
private $quality = 100;
private $x_input;
private $y_input;
private $x_output;
private $y_output;
private $resize;
// Set image
public function upload($orig, $name, $path)
{
move_uploaded_file($orig, __DIR__ . "/../uploads/" . $path . 'orig_' . $name);
}
public function set_img($img)
{
//$img = __DIR__ . '/../uploads/' . $img;
$img = '../uploads/' . $img;
// Find format
$ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));
// JPEG image
if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
{
$this->format = $ext;
$this->img_input = ImageCreateFromJPEG($img);
$this->img_src = $img;
}
// PNG image
elseif(is_file($img) && $ext == "PNG")
{
$this->format = $ext;
$this->img_input = ImageCreateFromPNG($img);
$this->img_src = $img;
}
// GIF image
elseif(is_file($img) && $ext == "GIF")
{
$this->format = $ext;
$this->img_input = ImageCreateFromGIF($img);
$this->img_src = $img;
}
// Get dimensions
$this->x_input = imagesx($this->img_input);
$this->y_input = imagesy($this->img_input);
}
// Set maximum image size (pixels)
public function set_size($size = 100)
{
// Wide
if($this->x_input >= $this->y_input && $this->x_input > $size)
{
$this->x_output = $size;
$this->y_output = ($this->x_output / $this->x_input) * $this->y_input;
$this->resize = TRUE;
}
// Tall
elseif($this->y_input > $this->x_input && $this->y_input > $size)
{
$this->y_output = $size;
$this->x_output = ($this->y_output / $this->y_input) * $this->x_input;
$this->resize = TRUE;
}
// Don't resize
else { $this->resize = FALSE; }
}
// Set image quality (JPEG only)
public function set_quality($quality)
{
if(is_int($quality))
{
$this->quality = $quality;
}
}
// Save image
public function save_img($path)
{
// Resize
if($this->resize)
{
$this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);
}
// Save JPEG
if($this->format == "JPG" OR $this->format == "JPEG")
{
if($this->resize) { imageJPEG($this->img_output, __DIR__ . "/../uploads/" . $path, $this->quality); }
else { copy($this->img_src, __DIR__ . "/../uploads/" . $path); }
}
// Save PNG
elseif($this->format == "PNG")
{
if($this->resize) { imagePNG($this->img_output, __DIR__ . "/../uploads/" . $path, 9); }
else { copy($this->img_src, __DIR__ . "/../uploads/" . $path); }
}
// Save GIF
elseif($this->format == "GIF")
{
if($this->resize) { imageGIF($this->img_output, __DIR__ . "/../uploads/" . $path); }
else { copy($this->img_src, __DIR__ . "/../uploads/" . $path); }
}
}
// Get width
public function get_width()
{
return $this->x_input;
}
// Get height
public function get_height()
{
return $this->y_input;
}
// Clear image cache
public function clear_cache()
{
#ImageDestroy($this->img_input);
#ImageDestroy($this->img_output);
}
}
And calling upload
$img = new imaging;
$img->upload($src['tmp_name'], $name, $dir);
$img->set_img($dir . 'orig_' . $name); // upload original file
$img->set_quality(100);
// Small thumbnail
$img->set_size(700); // upload thumbnail
$img->save_img($dir . $name);
// Finalize
$img->clear_cache();
Result isn't very good, instead of setting quality=100. Original file (width cca 1100px) is uploaded correctly (no resize on server), when I open it in Photoshop, resize to 700px width and compare with 700px thumb resized in PHP, there is very big difference in quality.
See both images, original resized in Photoshop (top) and resize image via PHP (bottom) - texts, images, etc. are blurred, colors aren't bright.
Orig size
200% zoom in Photoshop
Any ideas? Thanks for your replies :-)
I'm gonna answer here because I don't have enough reputation to make a comment.
To resize the image, i think it's better to use the command imagescale. It's better that use ImageCreateTrueColor + ImageCopyResampled.
So I'd do it
// Resize
if($this->resize)
{
$this->img_output = imagescale($this->img_input, $this->x_output, $this->y_output);
}
But there are some other things that you also may change:
I created the method create_thumbnail() and you'll pass it the path to the image, the path where save the new image and optionally the size (Default 100).
To have the width and the height, you don't need to create the image. You can do it with the method getimagesize and like this, you'll save a lot of resources.
When you call the method to resize, it will resize the image if it needed.
And when you are going to save the image, you can know if the image has been resized or not and so you'll copy it or not.
Also, I've tried to not repeat any code and optimising the resources.
EDIT: Also you can clear the cache and the end of the process.
class imaging
{
// Variables
private $img_input;
private $img_output;
private $img_src;
private $format;
private $quality = 100;
private $x_input;
private $y_input;
private $x_output;
private $y_output;
private $resize;
// Set image
public function upload($orig, $name, $path)
{
move_uploaded_file($orig, __DIR__ . "/../uploads/" . $path . 'orig_' . $name);
}
// Set image quality (JPEG only)
public function set_quality($quality)
{
if(is_int($quality))
{
$this->quality = $quality;
}
}
// Set maximum image size (pixels)
private function resize($size = 100)
{
$resize = FALSE;
// Wide
if($this->x_input >= $this->y_input && $this->x_input > $size)
{
$this->x_output = $size;
$this->y_output = ($this->x_output / $this->x_input) * $this->y_input;
$resize = TRUE;
}
// Tall
elseif($this->y_input > $this->x_input && $this->y_input > $size)
{
$this->y_output = $size;
$this->x_output = ($this->y_output / $this->y_input) * $this->x_input;
$resize = TRUE;
}
if($resize){
switch ($this->format) {
case 'JPEG':
case 'JPG':
$this->img_input = ImageCreateFromJPEG($img);
break;
case 'PNG':
$this->img_input = ImageCreateFromPNG($img);
break;
case 'GIF':
$this->img_input = ImageCreateFromGIF($img);
break;
default:
throw new Exception("This extension " . $ext . " it's not compatible.");
break;
}
}
}
// Save image
public function save_img($path)
{
// We have resized the image
if($this->img_input){
switch ($this->format) {
case 'JPEG':
case 'JPG':
imageJPEG($this->img_output, __DIR__ . "/../uploads/" . $path, $this->quality);
break;
case 'PNG':
imagePNG( $this->img_output, __DIR__ . "/../uploads/" . $path, 9);
break;
case 'GIF':
imageGIF( $this->img_output, __DIR__ . "/../uploads/" . $path);
break;
default:
throw new Exception("This extension " . $ext . " it's not compatible.");
break;
}
}else{
copy($this->img_src, __DIR__ . "/../uploads/" . $path);
}
}
public function create_thumbnail($imgSrc, $savePath, $size = 100)
{
$this->img_src = '../uploads/' . $img;
if(file_exists($this->img_src)){
list($this->x_input, $this->y_input) = getimagesize($imageSrc);
$this->format = strtoupper(pathinfo($img, PATHINFO_EXTENSION));
$this->resize($size);
$this->save_img($savePath);
$this->clear_cache();
}else{
throw new Exception("Image not found in " . $imdSrc);
}
}
// Get width
public function get_width()
{
return $this->x_input;
}
// Get height
public function get_height()
{
return $this->y_input;
}
// Clear image cache
public function clear_cache()
{
#ImageDestroy($this->img_input);
#ImageDestroy($this->img_output);
}
}
You can give this package a try http://image.intervention.io/getting_started/introduction . http://image.intervention.io/getting_started/installation, here it has all the configuration instruction.
It should work correctly and very easy to setup with composer.
I suggest you to use Intervention Image Library for image handling and manipulation. I have this type of issue in past and switching to a different library solved the issue.
Secondly, the use of this library is extremely simple which is already available on website.
I will recommend
convert your image into base64 then update the base64 string then on server side again covert that base64 string into image. you will find the method for conversion
image to base64: https://stackoverflow.com/a/13758760/11956865
base64 to image: https://stackoverflow.com/a/15153931/11956865

Compress & resize images using PHP GD lib not working for png and weird results for jpg

I am trying to compress & resize my images using the php GD library. Nearly every answer on SO and everywhere else is the same, but for my solution, the PNG's are not being correctly transformed, and some jpg's are giving bizarre results.
This is the code I am using:
public function resizeImages() {
ini_set('max_execution_time', 0);
//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = FCPATH . 'design/img/test/'; //Source Image Directory End with Slash
$DestImagesDirectory = FCPATH . 'design/img/test/thumb/'; //Destination Image Directory End with Slash
$NewImageWidth = 150; //New Width of Image
$NewImageHeight = 150; // New Height of Image
$Quality = 90; //Image Quality
//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImagesDirectory)){
while(($file = readdir($dir))!== false){
$imagePath = $ImagesDirectory.$file;
$destPath = $DestImagesDirectory.$file;
$checkValidImage = #getimagesize($imagePath);
if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
{
//Image looks valid, resize.
if (resize_image($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality))
{
echo $file.' resize Success!<br />';
/*
Now Image is resized, may be save information in database?
*/
} else {
echo $file.' resize Failed!<br />';
}
}
}
closedir($dir);
}
}
and the resize_image function looks like this:
function resize_image($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
list($iWidth,$iHeight,$type) = getimagesize($SrcImage);
$ImageScale = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
$NewWidth = ceil($ImageScale*$iWidth);
$NewHeight = ceil($ImageScale*$iHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
$imagetype = strtolower(image_type_to_mime_type($type));
switch($imagetype)
{
case 'image/jpeg':
$NewImage = imagecreatefromjpeg($SrcImage);
break;
case 'image/png':
$NewImage = imagecreatefrompng($SrcImage);
break;
default:
return false;
}
//allow transparency for pngs
imagealphablending($NewCanves, false);
imagesavealpha($NewCanves, true);
// Resize Image
if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
switch ($imagetype) {
case 'image/jpeg':
if(imagejpeg($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
case 'image/png':
if(imagepng($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
}
break;
default:
return false;
}
return true;
}
}
Every single png is not working, it just returns a file with 0 bytes and "file type is not supported", even though the type is recognized as .PNG in Windows...
Some JPG's return a weird result as well, see the following screenshot which indicates my issues regarding png's and some jpg's:
1) Do not use getimagesize to verify that the file is a valid image, to mention the manual:
Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.
$checkValidImage = exif_imagetype($imagePath);
if(file_exists($imagePath) && ($checkValidImage == IMAGETYPE_JPEG || $checkValidImage == IMAGETYPE_PNG))
2) While imagejpeg() accepts quality from 0 to 100, imagepng() wants values between 0 and 9, you could do something like that:
if(imagepng($NewCanves,$DestImage,round(($Quality/100)*9)))
3) Using readdir () you should skip the current directory . and the parent..
while(($file = readdir($dir))!== false){
if ($file == "." || $file == "..")
continue;
edit
Point 2 is particularly important, imagepng () accepts values greater than 9 but then often fails with error in zlib or libpng generating corrupt png files.
I tried resizing some png and jpeg and I didn't encounter any problems with these changes.

How to integrate php thumbnail creator with multiple image uploader script?

I have this code to upload multiple image. It is working fine.
<?php
include('db.php');
session_start();
$session_id='1'; //$session id
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$inputFileName = $_FILES['photoimg']['name'];
$actual_image_name = time().substr(str_replace(" ", "_", $ext), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
But I want to create thumbnail for per image. To do this I have another one. I have found it from a website...but I can't understand how to integrate with my original one.
function thumbnail($inputFileName, $maxSize = 100)
{
$info = getimagesize($inputFileName);
$type = isset($info['type']) ? $info['type'] : $info[2];
// Check support of file type
if ( !(imagetypes() & $type) )
{
// Server does not support file type
return false;
}
$width = isset($info['width']) ? $info['width'] : $info[0];
$height = isset($info['height']) ? $info['height'] : $info[1];
// Calculate aspect ratio
$wRatio = $maxSize / $width;
$hRatio = $maxSize / $height;
// Using imagecreatefromstring will automatically detect the file type
$sourceImage = imagecreatefromstring(file_get_contents($inputFileName));
// Calculate a proportional width and height no larger than the max size.
if ( ($width <= $maxSize) && ($height <= $maxSize) )
{
// Input is smaller than thumbnail, do nothing
return $sourceImage;
}
elseif ( ($wRatio * $height) < $maxSize )
{
// Image is horizontal
$tHeight = ceil($wRatio * $height);
$tWidth = $maxSize;
}
else
{
// Image is vertical
$tWidth = ceil($hRatio * $width);
$tHeight = $maxSize;
}
$thumb = imagecreatetruecolor($tWidth, $tHeight);
if ( $sourceImage === false )
{
// Could not load image
return false;
}
// Copy resampled makes a smooth thumbnail
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $tWidth, $tHeight, $width, $height);
imagedestroy($sourceImage);
return $thumb;
}
/**
* Save the image to a file. Type is determined from the extension.
* $quality is only used for jpegs.
* Author: mthorn.net
*/
function imageToFile($im, $fileName, $quality = 80)
{
if ( !$im || file_exists($fileName) )
{
return false;
}
$ext = strtolower(substr($fileName, strrpos($fileName, '.')));
switch ( $ext )
{
case '.gif':
imagegif($im, $fileName);
break;
case '.jpg':
case '.jpeg':
imagejpeg($im, $fileName, $quality);
break;
case '.png':
imagepng($im, $fileName);
break;
case '.bmp':
imagewbmp($im, $fileName);
break;
default:
return false;
}
return true;
}
$im = thumbnail('temp.jpg', 100);
imageToFile($im, 'temp-thumbnail.jpg');
Help will be greatly appreciated...
You can use following;
<?php
....
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
// Create thumbnail here
$thumb = thumbnail($path.$actual_image_name, "80"); // image name, and size
imageToFile($thumb, 'path/to/thumb/thumbnail_' . $session_id . '.jpg');
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
...
?>
Do not forget to add thumbnail and imageToFile to put in your php file
<?php
// thumbnail configuration
$thumb_width = 50;
$thumb_height = 50;
$thumb_method = 'crop';
$thumb_bgColour = null; //array(255,240,240);
$thumb_quality = 70;
// Let script run for as long as it needs to when creating thumbnails.
// Some web hosts won't let you use this function. In that case you'll need
// to comment it out and just refresh the script until it has thumbnailed all the images.
set_time_limit(0);
// include the thumbnail function
require_once dirname(__FILE__) . '/paGdThumbnail.php';
// get the path to the current directory
$path = dirname(__FILE__);
// get the url for the images
$path_info = pathinfo($_SERVER['SCRIPT_NAME']);
$url = $path_info['dirname'];
// create an array to store image names in.
$images = array();
//$dir = new DirectoryIterator($path);
$file_name=$_REQUEST['big_img'];//$_FILES['big_img']['name'];
$file_path=$path.'\\'.$file_name;
/*
Loop through the directory, finding all images that aren't thumbnails.
For each image:
- if it doesn't already have a thumbnail, or the thumbnail is older than the image,
create a thumbnail.
- get info about the image
- add the image to our images array
*/
if( preg_match('#^(.+?)(_t)?\.(jpg|gif|png)#i', $file_name, $matches)){
list( ,$name, $is_a_thumb, $extension) = $matches;
// if its not a thumbnail
if( !$is_a_thumb ){
// does a valid thumbnail exist?
$has_thumb = false;
$thumb_file = $path . '/' . $matches[1] . '_t.jpg';
if( file_exists($thumb_file) && filemtime($thumb_file) > filemtime($file_path) ){
$has_thumb = true;
}
else{
// no thumbnail, so we shall create one!
// create a gd image. reading the contents of the image file into a string, then
// using imagecreatefromstring saves having to check the filetype and which
// imagecreatefrom(jpeg/gif/png) function to use
$image = imagecreatefromstring(file_get_contents($file_path));
if( $image ){
// create the thumbnail
$thumb = paGdThumbnail($image, $thumb_width, $thumb_height, $thumb_method, $thumb_bgColour);
// free the image resource
imagedestroy($image);
if( $thumb ){
// save the thumbnail
if( imagejpeg($thumb, $thumb_file, $thumb_quality) ){
$has_thumb = true;
}
// free the memory used by the thumbnail image
imagedestroy($thumb);
}
}
}
if( $has_thumb ){
$images[$file_name] = $name;
}
}
}
// sort the images array so always in the same order
ksort($images);
// end or processing, now display the gallery
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Thumbnails :</title>
<style type="text/css">
<!--
#thumbs{
position: relative;
}
#thumbs div{
float: left;
width: <?php echo $thumb_width + 30?>px;
height: <?php echo $thumb_height + 30?>px;
text-align: center;
}
#thumbs a:link img, #thumbs a:visited img{
border: 1px solid #acacac;
padding: 5px;
}
#thumbs a:hover img{
border: 1px solid black;
}
-->
</style>
</head>
<body>
<div id="thumbs">
<?php foreach( $images as $imagename => $name ){ ?>
<div>
<img src="<?php echo $url . '/' . $name . '_t.jpg'?>" />
</div>
<?php }?>
</div>
</body>
</html>

How can insert 4 fileupload in one form

I need to know if is possible have in one form 4 fileupload, each one to save in different folder when a user want affiliate to our service.. like per example in first upload the Curriculum, next the photo and for the last two the diploma's..
Here is the form URL I am using right now and in "documentos" tab are all the input type file
here is my script
<?php
//----------------------------------------- start edit here ---------------------------------------------//
$script_location = "http://www.proderma.org/"; // location of the script
$maxlimit = 8388608; // maxim image limit
$folder = "uploads/foto_doc"; // folder where to save images
// requirements
$minwidth = 200; // minim width
$minheight = 200; // minim height
$maxwidth = 4608; // maxim width
$maxheight = 3456; // maxim height
$thumb3 = 1; // allow to create thumb n.3
// allowed extensions
$extensions = array('.png', '.gif', '.jpg', '.jpeg','.PNG', '.GIF', '.JPG', '.JPEG', '.docx');
//----------------------------------------- end edit here ---------------------------------------------//
// check that we have a file
if((!empty($_FILES["uploadfile"])) && ($_FILES['uploadfile']['error'] == 0)) {
// check extension
$extension = strrchr($_FILES['uploadfile']['name'], '.');
if (!in_array($extension, $extensions)) {
echo 'wrong file format, alowed only .png , .gif, .jpg, .jpeg
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else {
// get file size
$filesize = $_FILES['uploadfile']['size'];
// check filesize
if($filesize > $maxlimit){
echo "File size is too big.";
} else if($filesize < 1){
echo "File size is empty.";
} else {
// temporary file
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
// capture the original size of the uploaded image
list($width,$height) = getimagesize($uploadedfile);
// check if image size is lower
if($width < $minwidth || $height < $minheight){
echo 'Image is to small. Required minimum '.$minwidth.'x'.$minheight.'
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else if($width > $maxwidth || $height > $maxheight){
echo 'Image is to big. Required maximum '.$maxwidth.'x'.$maxheight.'
<script language="javascript" type="text/javascript">window.top.window.formEnable();</script>';
} else {
// all characters lowercase
$filename = strtolower($_FILES['uploadfile']['name']);
// replace all spaces with _
$filename = preg_replace('/\s/', '_', $filename);
// extract filename and extension
$pos = strrpos($filename, '.');
$basename = substr($filename, 0, $pos);
$ext = substr($filename, $pos+1);
// get random number
$rand = time();
// image name
$image = $basename .'-'. $rand . "." . $ext;
// check if file exists
$check = $folder . '/' . $image;
if (file_exists($check)) {
echo 'Image already exists';
} else {
// check if it's animate gif
$frames = exec("identify -format '%n' ". $uploadedfile ."");
if ($frames > 1) {
// yes it's animate image
// copy original image
copy($_FILES['uploadfile']['tmp_name'], $folder . '/' . $image);
} else {
// create an image from it so we can do the resize
switch($ext){
case "gif":
$src = imagecreatefromgif($uploadedfile);
break;
case "jpg":
$src = imagecreatefromjpeg($uploadedfile);
break;
case "jpeg":
$src = imagecreatefromjpeg($uploadedfile);
break;
case "png":
$src = imagecreatefrompng($uploadedfile);
break;
}
if ($thumb3 == 1){
// create third thumbnail image - resize original to 125 width x 125 height pixels
$newheight = ($height/$width)*600;
$newwidth = 600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagealphablending($tmp, false);
imagesavealpha($tmp,true);
$transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// write thumbnail to disk
$write_thumb3image = $folder .'/thumb3-'. $image;
switch($ext){
case "gif":
imagegif($tmp,$write_thumb3image);
break;
case "jpg":
imagejpeg($tmp,$write_thumb3image,100);
break;
case "jpeg":
imagejpeg($tmp,$write_thumb3image,100);
break;
case "png":
imagepng($tmp,$write_thumb3image);
break;
}
}
// all is done. clean temporary files
imagedestroy($src);
imagedestroy($tmp);
echo "<script language='javascript' type='text/javascript'>window.top.window.formEnable();</script>
<div class='clear'></div>";
}
}
}
}
// database connection
include('include/config.php');
$stmt = $conn->prepare('INSERT INTO INGRESOS (nombre,dui,nit,direccion,curriculum,pais,departamento,ciudad,telefono,email,universidad,diploma,jvpm,especializacion,diploma_esp,foto,website,contacto)
VALUES (:nombre,:dui,:nit,:direccion,:curriculum,:pais,:departamento,:ciudad,:telefono,:email,:universidad,:diploma,:jvpm,:especializacion,:diploma_esp,:foto,:website,:contacto)');
$stmt->execute(array(':nombre' => $nombre,':nit' => $nit,':direccion' => $direccion,':curriculum' => $path,':pais' => $pais,':departamento' => $departamento,':ciudad' => $ciudad,':departamento' => $departamento,':ciudad' => $ciudad,':telefono' => $telefono,':email' => $email,':universidad' => $universidad,':diploma' => $path1,':jvpm' => $jvpm,':especializacion' => $especializacion,':diploma_esp' => $path2,':foto' => $write_thumb3image,':website' => $website,':contacto' => $contacto));
echo 'Afiliación ingresada correctamente.';
$dbh = null;
}
// error all fileds must be filled
} else {
echo '<div class="wrong">You must to fill all fields!</div>'; }
?>
the files I need save only the path, so I have this:
:curriculum' => $path
:diploma' => $path1
:diploma_esp' => $path2
:foto' => $write_thumb3image
I don´t know if is possible these...I hope it can be.
Best Regards!
Include multiple file fields
<input type="file" name="file[0]" />
<input type="file" name="file[1]" />
<input type="file" name="file[2]" />
<input type="file" name="file[3]" />
Wrap a foreach around your save script
// set up your paths
$paths=array($path, $path1, $path2, $write_thumb3image);
// 0 1 2 3
// use them as your loop
foreach ($paths as $i=>$path){ // <- use an index $i
// *** save to $path.'/'.$your_image_name.$image_ext
// as Phillip rightly pointed out, $_FILES is different
// so using your index, pick out the bits from the $_FILES arary
$name=$_FILES['file']['name'][$i];
$type=$_FILES['file']['type'][$i];
$tmp_name=$_FILES['file']['tmp_name'][$i];
$size=$_FILES['file']['size'][$i];
$error=$_FILES['file']['error'][$i];
$extension = strrchr($name, '.'); // NB the file name does not mean that's the true extension
....
}
Untested

How can I allow other image formats to be uploaded

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);

Categories