Multiple image upload from webservice in php json form - php

I am creating a web service using php and json to upload multiple images
to move in the folder and in database, I am able to upload one image using this code
$image_binary=base64_decode($real_img);
$image_file = fopen("images/real/".time().$real_img.$id.'.jpg', 'wb');
fwrite($image_file, $image_binary);
$image_path = "".$id.'.jpg';
move_uploaded_file(fwrite($image_file, $image_binary), $image_path);
How can I use this code for multiple images if I get the multiple images in array.

Loop it:
(untested)
$images = array(0 => 'img1....jpg',
1 => 'img2....jpg');
uploadImages($images);
function uploadImages($images) {
for($i = 0; count($images) > $i; $i++) {
$image = $images[$i];
$image_binary=base64_decode($image);
$image_file = fopen("images/real/".time().$image.$id.'.jpg', 'wb');
fwrite($image_file, $image_binary);
$image_path = "".$id.'.jpg';
move_uploaded_file(fwrite($image_file, $image_binary), $image_path);
}
}

Related

How to reduce image quality / image size using php, we tried but not able to solve?

Here is a code what I am using to create image reducer but not getting solution
this code taking an image from my chosen path from the computer and uploading as is it, like same image size and same quality, but I want to reduce image size at the same ratio
<?php
include '../database/db.php';
include "../includes/session.php";
if(isset($_GET["d"]))
{
$output_dir=($_GET['d']);
$directory=($_GET['fp']);
$pid=($_GET['pid']);
$lid=($_GET['lid']);
$subjecta=($_GET['subject']);
}
if(isset($_FILES["myfile"]))
{
$ret = array();
$error =$_FILES["myfile"]["error"];
//You need to handle both cases
//If Any browser does not support serializing of multiple files using FormData()
if(!is_array($_FILES["myfile"]["name"])) //single file
{
$fileName = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
$ret[]= $fileName;
$path = "$directory$fileName";
$query = "INSERT INTO table_name (lid,pid,nots,filename)VALUES('$lid','$pid','$path','$fileName')";
$suc= mysql_query($query);
}else{
$fileCount = count($_FILES["myfile"]["name"]);
for($i=0; $i < $fileCount; $i++)
{
$fileName = $_FILES["myfile"]["name"][$i];
move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$fileName);
$ret[]= $fileName;
$path = "$directory$fileName";
$query = "INSERT INTO table_name (lid,pid,nots,filename)VALUES('$lid','$pid','$path','$fileName')";
$suc= mysql_query($query);
}
}
echo json_encode($ret);
}
?>
we made this code for a single file and multiple files
you should process the uploaded image on your server using something like ImageMagick, you can read more here http://php.net/manual/en/book.imagick.php
you can find some examples of image manipulation here:
http://php.net/manual/en/imagick.examples-1.php

resize multiple images while uploading

Hi im trying to resize multiple image while uploading i have the function that resize but its only work for one image so please can anyone shom me how to loop this for multiple file upload
if( $_FILES['image']['size']< $max_file_size ){
// get file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// $ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
if (in_array($ext, $valid_exts)) {
/* resize image */
foreach ($sizes as $w => $h) {
$files[] = resize($w, $h);
}
} else {
$msg = 'Unsupported file';
}
} else{
$msg = 'Please upload image smaller than 200KB';
}
This is untested, but might give you an idea.
The way this works is by looping through all of the $_FILES of the variable $iname which is 'image'. I set this since it's used multiple times, so if you ever change it, its easier.
I create a new variable called $image which will be the variables for that specific image. I do this by looping through all of the variables of $_FILES[$iname]. I set the $image variable to the $key and the new value, which will be an array. We reference the correct array using the $i variable.
Next I simply use your existing code. Since the resize() function only calls for width and height, I am unsure what happens here. Another parameter should be passed to reference the image you want to resize, which will be $image.
From the visible code I typed, not knowing what resize() is, this code is insecure. You should really check more than just the file extension since it can easily be changed. I usually use exif to check the image header. I also never store the data users upload unless I re-encode it using a GDI function in PHP.
Hopefully this will get you started.
$i = 0;
$iname = 'image';
for($i = 0; $i < count($_FILES[$iname]['size']); $i++) {
// Create new Image Array
$image = array();
foreach($_FILES[$iname] as $key => $val) {
$image[$key] = $val[$i];
}
if( $image['size'] < $max_file_size ) {
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
foreach ($sizes as $w => $h) {
// How is resize getting the $_FILES?
// Should pass a variable of $image and use it instead
$files[] = resize($w, $h);
}
} else {
$msg = 'Unsupported file';
}
} else{
$msg = 'Please upload image smaller than 200KB';
}
}

Saving Each PDF Page to an Image Using Imagick

I have the following php function below that's converting a local PDF file into images. In short, I want each PDF page to be converted to a separate image.
The function converts the PDF to an image - but only the last page. I want every page of the PDF to be converted to a image and numbered. Not just the last page of the PDF.
Currently, this function converts the last page of example.pdf to example-0.jpg. Issue I'm sure lies within the for method. What am I missing?
$file_name = 'example.pdf'; // using just for this example, I pull $file_name from another function
function _create_preview_images($file_name) {
// Strip document extension
$file_name = basename($file_name, '.pdf');
// Convert this document
// Each page to single image
$img = new imagick('uploads/'.$file_name.'.pdf');
// Set background color and flatten
// Prevents black background on objects with transparency
$img->setImageBackgroundColor('white');
$img = $img->flattenImages();
// Set image resolution
// Determine num of pages
$img->setResolution(300,300);
$num_pages = $img->getNumberImages();
// Compress Image Quality
$img->setImageCompressionQuality(100);
// Convert PDF pages to images
for($i = 0;$i < $num_pages; $i++) {
// Set iterator postion
$img->setIteratorIndex($i);
// Set image format
$img->setImageFormat('jpeg');
// Write Images to temp 'upload' folder
$img->writeImage('uploads/'.$file_name.'-'.$i.'.jpg');
}
$img->destroy();
}
Seems like most of my code was correct. The issue was, I was using $img->flattenImages(); incorrectly. This merges a sequence of images into one image. Much like how Photoshop flattens all visible layers into an image when exporting a jpg.
I removed the above line and the individual files were written as expected.
/* convert pdf file to list image files */
if($_FILES['file_any']['type']=='application/pdf'){
$file_name = str_replace(substr($url,0,strpos($url,$_FILES['file_any']['name'])),'',$url);
$basename = substr($file_name,0,strpos($file_name,'.'));
$abcd = wp_upload_dir();
$delpath = $abcd['path'];
$savepath = $abcd['url'];
$dirpath = substr($savepath,(strpos($savepath,'/upl')+1));
$file_name = basename($file_name, '.pdf');
$img = new imagick($delpath.'/'.$file_name.'.pdf');
$img->setImageBackgroundColor('white');
$img->setResolution(300,300);
$num_pages = $img->getNumberImages();
$img->setImageCompressionQuality(100);
$imageurl = NULL;
$imagedelurl = NULL;
for($i = 0;$i < $num_pages; $i++) {
$imageurl[]=$savepath.'/'.$basename.'-'.$i.'.jpg';
$imagedelurl[] = $delpath.'/'.$basename.'-'.$i.'.jpg';
// Set iterator postion
$img->setIteratorIndex($i);
// Set image format
$img->setImageFormat('jpeg');
// Write Images to temp 'upload' folder
$img->writeImage($delpath.'/'.$file_name.'-'.$i.'.jpg');
}
$img->destroy();
}
There is a much easier way without the loop, just use $img->writeImages($filename,false); and it will make a file per PDF-page. As you said, if you flatten the image first, it only saves 1 page.
first install
imagemagick
in your system or server
and then create
pdfimage
folder and put pdf file in this folder then run the code and upload it file
<?php
$file_name = $_FILES['pdfupload']['name']; // using just for this example, I pull $file_name from another function
//echo strpos($file_name,'.pdf');
$basename = substr($file_name,0,strpos($file_name,'.'));
//echo $_FILES['pdfupload']['type'];
//if (isset($_POST['submit'])){
if($_FILES['pdfupload']['type']=='application/pdf'){
// Strip document extension
$file_name = basename($file_name, '.pdf');
// Convert this document
// Each page to single image
$img = new imagick('pdfimage/'.$file_name.'.pdf');
// Set background color and flatten
// Prevents black background on objects with transparency
$img->setImageBackgroundColor('white');
//$img = $img->flattenImages();
// Set image resolution
// Determine num of pages
$img->setResolution(300,300);
$num_pages = $img->getNumberImages();
// Compress Image Quality
$img->setImageCompressionQuality(100);
$images = NULL;
// Convert PDF pages to images
for($i = 0;$i < $num_pages; $i++) {
$images[]=$basename.'-'.$i.'.jpg';
// Set iterator postion
$img->setIteratorIndex($i);
// Set image format
$img->setImageFormat('jpeg');
// Write Images to temp 'upload' folder
$img->writeImage('pdfimage/'.$file_name.'-'.$i.'.jpg');
}
echo "<pre>";
print_r($images);
$img->destroy();
}
//}
?>

Converting multipage pdf to multi images

I am trying to convert a multipage PDF File to images by using PHP Image magic extension.The problem is that instead of getting images corresponding to each page of the file, I am getting the last page of pdf as the output image. Here is the code:
$handle = fopen($imagePath, "w");
$img1 = new Imagick();
$img1->setResolution(300,300);
$img1->readImage(path to pdf file);
$img1->setColorspace(imagick::IMGTYPE_GRAYSCALE);
$img1->setCompression(Imagick::COMPRESSION_JPEG);
$img1->setCompressionQuality(80);
$img1->setImageFormat("jpg");
$img1->writeImageFile($handle);
What am I doing wrong?The convert command on commandline with the same parameters works.
Try something like this instead:
$images = new Imagick("test.pdf");
foreach($images as $i=>$image) {
$image->setResolution(300,300);
//etc
$image->writeImage("page".$i.".jpg");
}
Try writeImages function. It creates each page as one image and it gives file names for multiple images like this: yourimagename, yourimagename-1, yourimagename-2.... It increases automatically from 0 to your numberofpagesinPdf-1.
The code looks like this:
$imagick = new Imagick($file_handle);
$imagick->readImage();
$imagick->writeImages($yourImagename.'.jpg', false);
This will work for pdf having multiple pages as well as the single page.
$pdf_file = 'path/to/pdf/file.php';
$image = new imagick();
$image->setResolution(300,300);
$image->readImage($pdf);
$image->setImageFormat('jpg');
// Set all other properties
$pages = $image->getNumberImages();
if ($pages) {
foreach($image as $index => $pdf_image) {
$pdf_image->writeImage('destination/path/' . $index . '-image_file.jpg');
}
} else {
echo 'PDF doesn\'t have any pages';
}
Try something like this if you know number of pages of your pdf:
$images = new Imagick();
foreach ($pages as $p){
$im->readImage($PdfFile."[".$p."]"); //yourfile.pdf[0], yourfile.pdf[1], ...
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(82);
$im->setImageFormat( "jpg" );
//...
$image_out = "image_".$p.".jpg";
$im->writeImage($image_out);
}
$im->clear();
$im->destroy();
If you dont know number of pages, you could do something like this:
$images = new Imagick();
$im->readImage($PdfFile);
$pages = (int)$im->getNumberImages();
this worked for me
$file = "./path/to/file/name.pdf";
$fileOpened = #fopen($archivo, 'rb');
$images = new Imagick();
$images->readImageFile($fileOpened);
foreach ($images as $i => $image) {
$image->setResolution(300, 300);
$image->setImageFormat("jpg");
$image->setImageCompression(imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality(90);
$image->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$data_blob = $image->getImageBlob();
$ouput="./path/images/files/page" . $i . ".jpg";
file_put_contents($ouput, $data_blob);
}
#fclose($fileOpened);
I hope I can help you too

Splitting images from while loop and renaming in php

I am trying to get images from while loop and split them up at the period (.).. and then change the name of the image to ImageName + -resized. But I can not seem to figure out how to do this. Any help would be greatly appreciated!
So in short I have this: image.jpg and I want to create this image-resized.jpg: Here is my code:
<?php
$f = $_GET['f'];
$h = $_GET['h'];
$gp = $_GET['gp'];
//Create folder path
$path = "Fotos/".$f."/".$h."/".$gp."/";
//Get pictures from database
$getfolders = mysql_query("SELECT FolderName, Files FROM Files WHERE FolderDate = '$f' AND FolderHour = '$h' AND FolderName = '$gp'") or die(mysql_error());
//List pictures from database
while($row = mysql_fetch_array($getfolders)){
$img = $row['Files'];
//Seperate image at period(.)
$image = explode('.', $img);
//Get image name ----------------Here is where I need help!!
for($i = 0; $i < sizeof($image); $i++)
{
$imag = $image[$i];
}
?>
<div class="picture" id="pic"><img src="<?php echo $path; echo $imag ?>" alt="picture" /><?php echo $img?></div>
<?php
}
?>
Well, the simplest solution would be:
$image = explode('.', $img);
$extension = array_pop($image);
$resizedFileName = implode('.', $image) . "-resized.{$extension}";
But this solution does assume, that there are only simple extensions:
image.jpg => image-resized.jpg // ok
image.tar.gz => image.tar-resized.gz // not so ok
But if there are only simple extensions, this solution might be sufficient.
A better solution would be using SplFileInfo:
$fi = new SplFileInfo($image);
$resizedFileName = $fi->getBasename("." . $fi->getExtension()) . "-resized." . $fi->getExtension();
SplFileInfo::getExtensions() is available since PHP 5.3.6

Categories