This is my index.php file, i have uploaded and moved image from tmp folder to image folder and it's working properly. but now i want to trim image on display, every picture should be display of same size, i have tried lots of way but it's not working.
Need for help!!
<?php
require_once('appvars.php');
include 'db_connect.php';
$sql = "SELECT * FROM gitarwar";
$data = mysqli_query($dbc, $sql);
echo "<table>";
while ($row = mysqli_fetch_array($data))
{
echo '<tr><td>';
echo '<strong>' . $row['Score'] . '</strong><br/>';
echo '<strong>Name:</strong>' . $row['Name'] . '<br/>';
echo '<strong>Datetime:</strong>' . $row['Datetime'] . '<br/>';
echo '<img src="' .GW_UPLOADPATH . $row['Screenshot'] . '" alt="Score image" />';
echo "</tr>";
}
echo"</table>";
mysqli_close($dbc);
?>
I had a similar task before. My job was to check the image, and if it is smaller than my $newWidth or $newHeight, it added.
$imageUrl = [PATH OR URL TO YOUR IMAGE FILE];
$imageContent = file_get_contents($imageUrl);
$im = imagecreatefromstring($imageContent);
$width = imagesx($im);
$height = imagesy($im);
$newwidth = 300;
$newheight = 300;
$output = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($output, false);
$transparency = imagecolorallocatealpha($output, 0, 0, 0, 127);
imagefill($output, 0, 0, $transparency);
imagesavealpha($output, true);
imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);
//Show the image
header('Content-Type: image/png');
imagepng($output); //You can save it with another parameter what is a path
imagedestroy($output);
imagedestroy($im);
You need to change this line:
imagecopymerge($output, $im, ($width < 300 ? (300 - $width) / 2 : 0), ($height < 300 ? (300 - $height) / 2 : 0), 0, 0, $width, $height, 100);
to your size.
It's actually not exactly what you want, but it could be a good starting point.
You can trim the image when uploading it, by using imagecreatefrom(jpeg|png|gif) function.
$file = "images/" . $_FILES['image']['name'];
$tmp_file = $_FILES['image']['tmp_name'];
$type = $_FILES['images']['type'];
if (move_uploaded_file($tmp_file, $file)) {
chmod($file, 0777);
// check the type of image, you can do this for other types too, just change the imagecreatefrom function to the type you want to save the image as
if ($type === 'image/jpeg') {
$jpeg = imagecreatefromjpeg($file);
$jpeg_width = imagesx($jpeg);
$jpeg_height = imagesy($jpeg);
$new_width = imagesx($jpeg) / 4; // Fix the width of the thumb nail images, change the width of image here
$new_height = imagesy($jpeg) / 4; // change the height of image here
//new image
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $jpeg, 0, 0, 0, 0, $new_width, $new_height, $jpeg_width, $jpeg_height);
imagejpeg($new_image, $thumb);
chmod($thumb, 0777);
}
}
Related
I'm resizing and saving PNGs with PHP. The first example doesn't work, the PNG ends up being completely black, but the second example works. The first example doesn't have a transparent background but the second one does. Why doesn't the first example work? Is it a problem with the URL?
<?php
$id = "example";
//$originalFile = "https://th.bing.com/th/id/OIP.v_YT6iKMW6sOOVdCxVYQkwHaE8?pid=ImgDet&rs=1.png"; // Doesn't work
$originalFile = "https://cdn.globalxetfs.com/content/files/210618-China_Materials_02.png"; // Works
list($originalWidth, $originalHeight) = getimagesize($originalFile);
$originalImage = #imagecreatefrompng($originalFile);
$newHeight = 255;
$newWidth = 255;
// Create empty canvas
$resizedImage = "";
$resizedImage = imagecreatetruecolor($newWidth, $newHeight); // width, height
// Preserve transparency
imagesavealpha($resizedImage, true);
$color = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
imagefill($resizedImage, 0, 0, $color);
// Resize image
imagecopyresampled(
$resizedImage, $originalImage, 0, 0, 0, 0,
$newWidth, $newHeight, $originalWidth, $originalHeight
);
header('Content-type: image/png');
$imageName = $id;
$imageName = $imageName . ".png";
if(imagepng($resizedImage, "images/" . $imageName)){
echo "Image uploaded";
}
?>
The "first example" actually is a JPG file (after the server image rendering) , so you need to use
#imagecreatefromjpeg instead of #imagecreatefrompng
So the codes (working) should be:
<?php
$id = "example";
$originalFile = "https://th.bing.com/th/id/OIP.v_YT6iKMW6sOOVdCxVYQkwHaE8?pid=ImgDet&rs=1.png";
//$originalFile = "https://cdn.globalxetfs.com/content/files/210618-China_Materials_02.png";
list($originalWidth, $originalHeight) = getimagesize($originalFile);
$originalImage = #imagecreatefromjpeg($originalFile);
$newHeight = 255;
$newWidth = 255;
// Create empty canvas
$resizedImage = "";
$resizedImage = imagecreatetruecolor($newWidth, $newHeight); // width, height
// Preserve transparency
imagesavealpha($resizedImage, true);
$color = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
imagefill($resizedImage, 0, 0, $color);
// Resize image
imagecopyresampled(
$resizedImage, $originalImage, 0, 0, 0, 0,
$newWidth, $newHeight, $originalWidth, $originalHeight
);
header('Content-type: image/png');
//$imageName = $id;
//$imageName = $imageName . ".png";
//if(imagepng($resizedImage, "images/" . $imageName)){
// echo "Image uploaded";
//}
imagepng($resizedImage);
?>
I am trying to upload an image using a form, everything so far in the form functions well except i get this error after i submit the form and the data gets submitted to the database table : **
Notice>: Undefined offset: 1 in D:\wamp\www\asserter\includes\create_thumbnail.php on line 40
this is the line 40 in the create_thumbnail() function : imagecopyresampled($thumb, $src, 0, 0, $src_pos[0], $src_pos[1], $new_size[0], $new_size[1], $size[0], $size[1]);
if comment the create_thumbnail() in my codes everything works fine and the image gets uploaded and i get no error back, but when i add create_thumbnail() line of code the original image does not get uploaded to the path but the thumbnail gets created and i still get this error ! please help !
here is my codes :
if ($_FILES["discussion_image"]["name"] != "") {
$test = explode(".", $_FILES["discussion_image"]["name"]);
$extension = end($test);
$name = rand(100, 9999999999);
$file_temp = $_FILES['discussion_image']['tmp_name'];
$file_path = '../uploaded_pictures/uploads/' . $user_id . '/'. $name .'.'.$extension;
//$file_path = mysqli_real_escape_string($connection, $file_path);
move_uploaded_file($file_temp, $file_path); // move_uploaded_file() is a built in function of PHP
$query = "INSERT INTO discussions_table (user_id, title, link, image_link, subject, discussion, discussion_timestamp) VALUES ($user_id, '$title', '$link', '$file_path', '$subject', '$discussion', $discussion_timestamp)";
$save_path = '../uploaded_pictures/uploads/' . $user_id . '/'. $name.'.jpg';
//$save_path_small = "../uploaded_pictures/uploads/" . $user_id . "/" . $name.'small.jpg';
create_thumbnail($file_path, $save_path, 250, 250); // creates thumbnail for profile picture
//create_thumbnail($file_path, $save_path_small, 50, 50); // creates thumbnail for small user picture
}
and here is my create_thumbnail function :
function create_thumbnail($path, $save, $width, $height) {
$info = getimagesize($path);
$size = array($info[0], $info[1]); // info[0] is the width and info[1] is the height
if ($info['mime'] == 'image/png') {
$src = imagecreatefrompng($path);
} else if ($info['mime'] == 'image/jpeg') {
$src = imagecreatefromjpeg($path);
} else {
return false;
}
$thumb = imagecreatetruecolor($width, $height);
$src_aspect = $size[0] / $size[1];
$thumb_aspect = $width / $height;
if ($src_aspect < $thumb_aspect) {
// means the image is narrower so we want to crop the top and bottom
$scale = $width / $size[0]; // width of the thumb and width of the actual image
$new_image = array($width, $width / $src_aspect);
$src_pos = array(0, ($size[1] * $scale - $height) / $scale / 2); // we are fixing x position to 0 and calculating the y position
} else if ($src_aspect > $thumb_aspect) {
// means image is wider so we need to crop left and right
$scale = $height / $size[1];
$new_size = array($height * $src_aspect, $height);
$src_pos = array(($size[0] * $scale - $width) / $scale / 2); // we are fixing y position to 0 and calculating the x position
} else {
// this means it is the same shape as the thumbnail we are creating
$new_size = array($width, $height);
$src_pos = array(0, 0);
}
$new_size[0] = max($new_size[0], 1);
$new_size[1] = max($new_size[1], 1);
imagecopyresampled($thumb, $src, 0, 0, $src_pos[0], $src_pos[1], $new_size[0], $new_size[1], $size[0], $size[1]);
if ($save === false) {
return imagejpeg($thumb);
} else {
return imagejpeg($thumb, $save);
}
}
Thanks everyone for your help, I found the bug !
it was a naming issue, i should replace this $new_image = array($width, $width / $src_aspect); with this $new_size = array($width, $width / $src_aspect);
I'm trying to take in two sets of x-y co-ordinates from an image in a 7:9 aspect ratio and replace the original image with the cropped section in a 280x360 image, but it's not working. It's not throwing up any errors but the image replacement after cropping doesn't seem to work. Echoing data tells me it takes in everything up to the imagecopyresampled code.
$formDatax1=$_POST["x1"];
$formDatax2=$_POST["x2"];
$formDatay1=$_POST["y1"];
$formDatay2=$_POST["y2"];
$filename='http://pathtofiles/path/photo/'.$a_photo;
$image_info = getimagesize($filename);
switch(strtolower($image_info['mime'])){
case 'image/png' : $image = imagecreatefrompng($filename); $imgtype='png'; break;
case 'image/jpeg': $image = imagecreatefromjpeg($filename); $imgtype='jpg'; break;
case 'image/gif' : $image = imagecreatefromgif($filename); $imgtype='gif'; break;
default: die();
}
$resized_width = ((int)$formDatax2) - ((int)$formDatax1);
$resized_height = ((int)$formDatay2) - ((int)$formDatay1);
$resized_image = imagecreatetruecolor(280, 360);
imagecopyresampled($resized_image, $image, 0, 0, (int)$formDatax1, (int)$formDatay1, 280, 360, $resized_width, $resized_height);
if ($imgtype=='png') {
imagepng($resized_image, $filename);
}
if ($imgtype=='jpg') {
imagejpeg($resized_image, $filename);
}
if ($imgtype=='gif') {
imagejpeg($resized_image, $filename);
}
echo '<script type="text/javascript">alert("Image cropped!"); </script>';
exit();
You're not specifying a new value for $filename. The http[s] URL wrappers can retrieve a file, but not write. You'll need to specify a local filesystem location to save the image to.
This solution is from PHP cookbook 3rd edition
Use the ImageCopyResampled() function, scaling the image as needed.
To shrink proportionally:
$filename = __DIR__ . '/php.png';
$scale = 0.5; // Scale
// Images
$image = ImageCreateFromPNG($filename);
$thumbnail = ImageCreateTrueColor(
ImageSX($image) * $scale,
ImageSY($image) * $scale);
// Preserve Transparency
ImageColorTransparent($thumbnail,
ImageColorAllocateAlpha($thumbnail, 0, 0, 0, 127));
ImageAlphaBlending($thumbnail, false);
ImageSaveAlpha($thumbnail, true);
// Scale & Copy
ImageCopyResampled($thumbnail, $image, 0, 0, 0, 0,
ImageSX($thumbnail), ImageSY($thumbnail),
ImageSX($image), ImageSY($image));
// Send
header('Content-type: image/png');
ImagePNG($thumbnail);
ImageDestroy($image);
ImageDestroy($thumbnail);
To shrink to a fixed-size rectangle:
// Rectangle Version
$filename = __DIR__ . '/php.png';
// Thumbnail Dimentions
$w = 50; $h = 20;
// Images
$original = ImageCreateFromPNG($filename);
$thumbnail = ImageCreateTrueColor($w, $h);
// Preserve Transparency
ImageColorTransparent($thumbnail,
ImageColorAllocateAlpha($thumbnail, 0, 0, 0, 127));
ImageAlphaBlending($thumbnail, false);
ImageSaveAlpha($thumbnail, true);
// Scale & Copy
$x = ImageSX($original);
$y = ImageSY($original);
$scale = min($x / $w, $y / $h);
ImageCopyResampled($thumbnail, $original,
0, 0, ($x - ($w * $scale)) / 2, ($y - ($h * $scale)) / 2,
$w, $h, $w * $scale, $h * $scale);
// Send
header('Content-type: image/png');
ImagePNG($thumbnail);
ImageDestroy($original);
ImageDestroy($thumbnail);
I'm experimenting with php script via ajax which uploads an array of images from this source.
While it works excellent I'm trying to enter php code which resizes images to 120px by width or height (whichever is larger).
For my sanity please help how to update code:
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
You can install imagemagick on your server:
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
$img = new Imagick($file);
if ($crop) {
$img->cropThumbnailImage($w, $h);
} else {
$img->thumbnailImage($w, $h, TRUE);
}
return $img;
}
resize_image(‘/path/to/some/image.jpg’, 150, 150);
Another way would be using the PHP-GD:
<?php
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
$img = resize_image(‘/path/to/some/image.jpg’, 150, 150);
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Output
imagejpeg($image_p, null, 100);
Find more at php.net
Well, I took an example of "promaty" from this LINK and call from loop:
<?php
$dir = "uploads/*.*";
$images = glob( $dir );
foreach( $images as $file ):
$px = 120;
$prefix = $px . "_";
$dst = "uploads/" . $prefix . basename($file);
$resized = image_resize($file, $dst, $px, $px);
echo "<img src='" . $dst . "' />";
echo "<p>" . basename($dst) . " </p>";
endforeach;
...and thanks for your time.
I have a class to read and output the image content, if $width is set, it will resize the image, and then output it.
If I call the function like this $image->readImage('123.jpg'); , it can output the image file correctly, but when I call $image->readImage('123.jpg', 300); to resize it, it just display a black image with resized width & height.
And I tried to replace the code from
#imagejpeg($thumb, null, 100);
to
#imagejpeg($image, null, 100);
will works~
-
protected function readImage($fileName, $width = 0)
{
if ($width <= 0) {
return #file_get_contents($this->destination . '/' . $fileName);
} else {
$imageSize = #getimagesize($this->destination . '/' . $fileName);
$actualWidth = $imageSize[0];
$actualHeigth = $imageSize[1];
if ($actualWidth <= $width) {
return #file_get_contents($this->destination . '/' . $fileName);
}
$height = (100 / ($actualWidth / $width)) * .01;
$height = #round($actualHeigth * $height);
$image = #imagecreatefromjpeg($this->destination . '/' . $fileName);
$thumb = #imagecreatetruecolor($width, $height);
#imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $actualWidth, $actualHeight);
ob_start();
#imagejpeg($thumb, null, 100);
$bits = ob_get_contents();
ob_end_clean();
return $bits;
}
}
Any experts know what happened and help me to solve it ?
Thanks.
you've been inconsistant in your spelling of $actualHeight vs $actualHeigth
if you didn't have so many # everywhere, then php would have told you this.