Image Resize and Upload - php

I am trying to upload some images using import.csv file. The images need to be resized before uploading. I am using this code for uploading but it is returning a black image of the given size.
<?php
error_reporting(E_ALL);
include('config.php');
include('inc/header.php');
define('CSV_PATH', '');
$csv_file = CSV_PATH . "importImage.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgets($csvfile, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$url = $insert_csv['url'] = $csv_array[0];
$image = $insert_csv['image'] = $csv_array[1];
$raw = file_get_contents($url . $image);
/*RESIZE USING GD*/
/*
* PHP GD
* resize an image using GD library
*/
// File and new size
//the original image has 800x600
$filename = $raw;
//the resize will be a percent of the original size
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = 200;
$newheight = 200;
// Load
$thumb = imagecreate($newwidth, $newheight);
$source = imagecreate($filename);
// Resize
$imgnew = imagecopyresampled($thumb, $source, 0, 0, 0, 0, newwidth, $newheight, $width, $height);
imagejpeg($thumb, 'Mypath' . time() . '.jpg'); // save resized image to
//Output and free memory
imagedestroy($thumb);
$i++;
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>

The following script will easily allow you to resize images using PHP and the GD library.
https://github.com/nomisoft/White-Hat-Classes/tree/master/Simple-Image

First, check that the $url.$image is a real image.
Second, getimagesize requires an image path, not the image
I'm pretty sure you want this: http://runnable.com/UnF-tFdudNt1AABt/how-to-resize-an-image-using-gd-library-for-php

Related

php image resizing but not saving after resizing

i am trying to upload image and then resizing the image and save it. the upload is working fine and the resizing is also working but the resized image is not saving. if i use header ("Content-type: image/jpeg"); then it showing the resized image also. but after resizing the image is not getting saved.
here is my code:
$filename = $_FILES['myfile']['name'][$count] ;
$filename = uploadfilename($filename);
$filename1=$iiid."blog".$filename;
$target_path = "../photo/";
$target_path = $target_path . repc($filename1);
move_uploaded_file($_FILES['myfile']['tmp_name'][$count], $target_path);
$dbfield = $count+1;
$sql="update product set img_".$dbfield." ='".rep($filename1)."' where id='".$iiid."'";
$result=mysql_query($sql);
$count++;
// header ("Content-type: image/jpeg");
// print_r(get_resource_type($uploadedImage));exit();
// $resizedImage = PIPHP_ImageResize($target_path,400,400);
$w = 100;
$h = 100;
list($width, $height) = #getimagesize($target_path);
$source = #ImageCreateFromJPEG($target_path);
$resized_img = #ImageCreateTrueColor($w, $h);
#ImageCopyResampled($resized_img, $source, 0, 0, 0, 0, $w, $h, $width, $height);
#ImageJPEG($resized_img);

Image file size smaller form base64 encode

There is tow image in base64 format ($theme_image_enc and $theme_image_enc_little). Now I want to make the second image ($theme_image_enc_little) size smaller like 15kb. How can do that?
$image = ($_FILES["my_image"]["name"]);
$theme_image = ($_FILES["my_image"]["tmp_name"]);
$bin_string = file_get_contents("$theme_image");
$theme_image_enc = base64_encode($bin_string);
$WIDTH = 400; // The size of your new image
$HEIGHT = 300; // The size of your new image
$QUALITY = 100; //The quality of your new image
$org_w = 850;
$org_h = 660;
$theme_image_little = imagecreatefromstring(base64_decode($theme_image_enc));
$image_little = imagecreatetruecolor($WIDTH, $HEIGHT);
imagecopyresampled($image_little, $theme_image_little, 0, 0, 0, 0, $WIDTH, $HEIGHT, $org_w, $org_h);
ob_start();
imagepng($image_little);
$contents = ob_get_contents();
ob_end_clean();
echo $theme_image_enc_little = base64_encode($contents);
try to show low image size in the browser you need to reduce the quality using with imagejpeg function
// Take value between $quality = (0 < 100)
imagejpeg($theme_image_enc_little, NULL, $quality);

Resize image from Rackspace container, save image in memory as new image in container?

I have a script that upload an image file to rackspace container, what I want to happen after that is
Create a copy of that image file.
Put the file into memory and resize the image.
Upload the file to the rackspace container with new file name.
Trouble is I'm not sure how to take the resampled image in memory and upload to rackspace container. Here is code.
$objectStoreService = $client->objectStoreService(null, 'IAD');
$container = $objectStoreService->getContainer(IMAGE_CONTAINER_NAME);
$fileData = fopen($_FILES['file-0']['tmp_name'], 'r');
$uniqid = uniqid();
$new_file_path = $uniqid."/".$_FILES['file-0']['name'];
$sm_file_path = $uniqid . "/" . 'sm_' .$_FILES['file-0']['name'];
// Upload filepath to database
$user->upload_profile_pic($new_file_path, $sm_file_path);
$result = $container->uploadObject($new_file_path, $fileData);
$new_file_path = IMAGE_CONTAINER_LINK."/".$new_file_path;
// Make Thumbnail of original image
$percent = 0.5; // percentage of resize
// Image to be changed.
$original_image = imagecreatefromjpeg($new_file_path);
list($width, $height) = getimagesize($new_file_path);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Temporary blank image in memory of height/width
$tmp_image = imagecreatetruecolor($new_width, $new_height);
// Copies the source image and copies into it the blank image and resamples it.
imagecopyresampled($tmp_image, $original_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save the image in memory
imagejpeg($tmp_image, NULL, 100);
// read the file
// Not sure how to put image in memory to rackspace cloud.
$fileData = fopen($tmp_image, 'r');
$tmp_image = imagecreatefromstring(file_get_contents($new_file_path));
$fileData = fopen($tmp_image, 'r');
$result = $container->uploadObject($sm_file_path, $fileData);
$response = array('image_path' => $new_file_path);
header('HTTP/1.1 201 Created');
echo json_encode($response);

How to auto resize uploaded image using php

I have a script;
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
// get the file extension first
$ext = substr(strrchr($fileName, "."), 1);
// make the random file name
$randName = md5(rand() * time());
// and now we have the unique file name for the upload file
$filePath = $imagesDir . $randName . '.' . $ext;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
which am using to upload images but I would like to add a script to resize the image to a specific size before it's uploaded. How do I do that???
EDIT: I have updated this to include your script elements. I'm starting from the point where you obtain your filename.
Here is a very quick, simple script to do it:
$result = move_uploaded_file($tmpName, $filePath);
$orig_image = imagecreatefromjpeg($filePath);
$image_info = getimagesize($filePath);
$width_orig = $image_info[0]; // current width as found in image file
$height_orig = $image_info[1]; // current height as found in image file
$width = 1024; // new image width
$height = 768; // new image height
$destination_image = imagecreatetruecolor($width, $height);
imagecopyresampled($destination_image, $orig_image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// This will just copy the new image over the original at the same filePath.
imagejpeg($destination_image, $filePath, 100);
Well, you can't change the size of it before it's uploaded, but you can use the GD Library to change the size of it after it's on the server. Check out GD and Image Functions listing for all of the related functions for dealing with images.
There is also this tutorial that will show you a custom class for doing a resize, but unless you need the whole think you can focus on the function resize to see how it's done

Resize images in PHP without using third-party libraries?

In one of my applications, I'm using the code snippet below to copy uploaded images to a directory. It works fine but copying large images (> 2MB) takes more time than ideal and I really don't need images this big, so, I'm looking for a way to resize the images. How to achieve this using PHP?
<?php
$uploadDirectory = 'images/0001/';
$randomNumber = rand(0, 99999);
$filename = basename($_FILES['userfile']['name']);
$filePath = $uploadDirectory.md5($randomNumber.$filename);
// Check if the file was sent through HTTP POST.
if (is_uploaded_file($_FILES['userfile']['tmp_name']) == true) {
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['userfile']['size'] <= 5000000) {
// Move the file to the path specified.
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filePath) == true) {
// ...
}
}
}
?>
Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
To anyone else seeking a complete example, create two files:
<!-- send.html -->
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<center>
<div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">
Select an image.
<br/>
<br/>
<form action="receive.php" enctype="multipart/form-data" method="post">
<input type="file" name="image" size="40">
<input type="submit" value="Send">
</form>
</div>
</center>
</body>
<?php
// receive.php
$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";
echo "File path:".$filePath."<br/>";
if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {
echo "File successfully received through HTTP POST.<br/>";
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['image']['size'] <= 5000000) {
echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";
// Resize and save the image.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
// Save the original image.
if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {
echo "Copied the original file to the specified destination.<br/>";
}
}
}
?>
I made a small function to resize images, the function is below:
function resize_image($path, $width, $height, $update = false) {
$size = getimagesize($path);// [width, height, type index]
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
if ( array_key_exists($size['2'], $types) ) {
$load = 'imagecreatefrom' . $types[$size['2']];
$save = 'image' . $types[$size['2']];
$image = $load($path);
$resized = imagecreatetruecolor($width, $height);
$transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
imagesavealpha($resized, true);
imagefill($resized, 0, 0, $transparent);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
imagedestroy($image);
return $save($resized, $update ? $path : null);
}
}
And here's how you use it:
if ( resize_image('dir/image.png', 50, 50, true) ) {// resize image.png to 50x50
echo 'image resized!';
}
there is 1 very simple image re-size function for all image types that keeps transparency and is very easy to use
check out :
https://github.com/Nimrod007/PHP_image_resize
hope this helps
ImageMagick is the fastest and probably the best way to resize images in PHP. Check out different examples here. This sample shows how to resize and image on upload.
Thanks to Mateus Nunes!
i edited his work a bit to get transparent pngs working:
$source = $_FILES["..."]["tmp_name"];
$destination = 'abc/def/ghi.png';
$maxsize = 45;
$size = getimagesize($source);
$width_orig = $size[0];
$height_orig = $size[1];
unset($size);
$height = $maxsize+1;
$width = $maxsize;
while($height > $maxsize){
$height = round($width*$height_orig/$width_orig);
$width = ($height > $maxsize)?--$width:$width;
}
unset($width_orig,$height_orig,$maxsize);
$images_orig = imagecreatefromstring( file_get_contents($source) );
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
$images_fin = imagecreatetruecolor($width,$height);
imagesavealpha($images_fin,true);
$trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127);
imagefill($images_fin,0,0,$trans_colour);
unset($trans_colour);
ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
unset($photoX,$photoY,$width,$height);
imagepng($images_fin,$destination);
unset($destination);
ImageDestroy($images_orig);
ImageDestroy($images_fin);
You could also use an x*y/width method for resizing and then calling imagecopyresampled() like is shown at http://www.virtualsecrets.com/upload-resize-image-php-mysql.html That page also puts images (after resizing) into mySQL via the PDO.

Categories