PHP - Imagemagick Changes Image Shape
Hi all
I have created the below script to resize my images and it works fine for landscape images but if you select a portrait image it saves it as a landscape image. How do I modify the script so it keeps the same aspect ratio? Code: [Select] copy($_FILES['image1']['tmp_name'], WEB_UPLOAD."images/adverts/test/".$_FILES['image1']['name']) or die("Error uploading image."); $ext = strtolower(substr($_FILES['image1']['name'], strrpos($_FILES['image1']['name'], "."))); $rand = rand(1, 100000000000000); $name = $rand . $ext; $image_small = $rand . $ext; rename(WEB_UPLOAD."images/adverts/test/".$_FILES['image1']['name'], WEB_UPLOAD."images/adverts/test/".$name) or die("Error renaming image.");; $go = WEB_UPLOAD.'images/adverts/test/'.$name; $stop = WEB_UPLOAD.'images/adverts/test/'.$image_small; exec ("/usr/bin/convert $go -resize 10%\> -quality 100 $stop"); unset($scale, $go, $stop); Many thanks for your help. Pete Similar TutorialsHi!
I would like to get some tips/ snippets about recognising a desired shape/ pattern inside a picture with the help of PHP.
I want to crop fixed areas (using percentages) of an image containing an identity card but, in order to do this, first I have to detect the boundaries of the identity card and crop the image so that there will be nothing left in it except the card. The identity card contained in the picture will not be rotated (not more than a few degrees) and the background may vary.
My final goal is to use the cropped areas with an OCR. I thought that this method will be good for removing the unwanted parts and also helping out the OCR. If you have a better idea, tell me.
Thank you!
(1) What does this actually do? (compress it?) $image = imagecreatefromjpeg("image.jpg"); header('Content-Type: image/jpeg'); imagejpeg($image); By using this rather than displaying by using www.site.com/image.jpg it reduces file size of an image from 2.5mb to 0.5mb !! (2) ImageMagick can't get these results. Am I doing something wrong? If I change the pixel size of an image in ImageMagick then I can reduce its file size, but (1) above reduces file size regardless of changing pixel size. Hi all I need to re-write the below code so that it doesn't use the exec function: Code: [Select] $scale = '74x74'; $go = WEB_UPLOAD.'/test/images/'.$image; $stop = WEB_UPLOAD.'/test/images/'.$image_small; exec ("/usr/bin/convert $go -resize $scale\> -quality 100 $stop") or die("Error creating 74 x 74 image."); Many thanks for your help. Pete I have a line of code that has been working for over a year, then two days ago it failed in a few areas on my site and I hadnt made any changes. I contacted the host and there was no server updates etc. Its a php/imagemagick issue, basically the "widthxheight^ - Minimum values of width and height given, aspect ratio preserved" command does not work and fails to import the image at all when I add ^ to my code. I need it though and im getting fustrated, for now ive changed my code to: exec("convert $path1 -thumbnail 200x180 -colorspace rgb -gravity center -extent 170x150 $path2"); which works ok but is not spot on like it was before, what I really want is exec("convert $path1 -thumbnail 170x150^ -colorspace rgb -gravity center -extent 170x150 $path2"); What ever I do I cant get ^ to work anymore but oddly all other imagemagick commands are fine. Hi all I am trying to resize an image using imagemagick but it won't let me use the below code as it shows a security error 'exec() has been disabled for security reasons': Code: [Select] $scale = '158x158'; $go = WEB_UPLOAD.'/test/images/'.$image; $stop = WEB_UPLOAD.'/test/images/'.$image_medium; exec("/usr/bin/convert $go -resize $scale\> -quality 100 $stop") or die("Error creating 158 x 158 image."); unset($scale, $go, $stop); How do I write the code that resizes the image without using the exec function? Many thanks for you help! Pete Hi all I'm using MAMP and trying to install ImageMagick. Is there a way to test if it is correctly installed when using MAMP? ttmt Here is the code I have right now:
<?php header('Content-type: image/png'); $grey = new ImagickPixel('#ebebeb'); $orange = new ImagickPixel('#0f92d6'); $image = new Imagick('assets/lop.png'); $layer = new Imagick('assets/lop-base.png'); $layer->thumbnailImage(200, 0); $image->thumbnailImage(200, 0); $layer->paintOpaqueImage($grey, $orange, 100); // Place layer on image $image->compositeImage($layer, Imagick::COMPOSITE_SOFTLIGHT, 0, 0); // Let's merge all layers (it is not mandatory). $image->flattenImages(); echo $image; ?>It's putting the layers on top of eachother very nice. The thing is is that this involves some heavy shading at times depending on the bunny breeds. Here is what the base image ($image) looks like: And here is what the overlay ($layer) looks like: This is what the outcome looks like versus the intended result: I've tried almost all of their composite constants.. I can't figure out how to do this or the best way of going about it. Because the colors are going to be dynamic throughout the site so I can't just save a .png of every color combination.. and there will be more colors layered on top of eachother like markings/patterns/etc. Thanks for any help! This topic has been moved to Other Web Server Software. http://www.phpfreaks.com/forums/index.php?topic=346533.0 Need to change the letter spacing.. help? $tag = 'www.xxxxxx.com'; $text_draw->setFontSize(8); $text_draw->setFillColor("black"); $output_image->annotateImage($text_draw, 123, 34, 0, $tag); $text_draw->setFillColor("white"); $output_image->annotateImage($text_draw, 122, 33, 0, $tag); Hi I'm trying to resize pictures for thumbnails I can do this correctly at linux command line with the following command convert ideologies.jpeg -resize 300x200 ./Thumbnails/testphp.jpg However trying to wrap this in PHP doesn't seem to work // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; exec("convert {['fileName']} -resize 300x200 wankertestphp.jpg"); } If you look above I do successfully hit the "The File has been uploaded successfully" line so it is entering that If statement. I've also checked the Threads table with a Select * from Threads and I can see the $fileName variable is entering there. I've tried numerous different ways around the $fileName variable (removing the brackets...removing the brackets and the apostrophes")
Any help is appreciated. Hi, Very new to PHP and am enjoying learning the ins and outs etc, but while creating my mam a website, ive ran into a problem while uploading, resizing and saving the file to my web host. Initially i used imagecreatefromjpeg, but this was taking too much memory up, so opted to use imagemagick. All of the features work apart from the file getting saved to the uploads directory on my web space. They always get saved to the root. If someone could help i would be very grateful. The code ive got currently is: <?php // If the form has been submitted do this if(isset($_POST['submit'])) { // Temporary upload image name $original_image = $_FILES['photo']['tmp_name']; // Get the image dimensions $size=GetImageSize( $original_image ); // Name to save the image as - in this case the same as the original $new_image = $_FILES['photo']['name']; // Maximum image width $max_width = "600"; // Maximum image height $max_height = "300"; // Resize the image and save exec("convert -size {$size[0]}x{$size[1]} $original_image -thumbnail $max_widthx$max_height $new_image"); echo "File uploaded<br>"; echo "<img src=\"".$new_image."\">"; } ?> Hopefully someone could help Many thanks, Matk. hello dear php-experts and freaks how to view photos and to rapidly change the major categories i have several hundred images (photographs) taht i want to view on opensuse linux version 13.1 i want to view the images - and of while doing so i want to turn the colored images into b/w Question; which is the best - ie. the quickest way to do so. note; i have installed the following thigns on my opensuse 13.1: - gimp the great grahical tool - digicam - the great tool to view images and pictures - Gwenview Version 4.11.4 on KDE 4.11.5 so again here the question: which tool allowes to view the color(ed) image and to turn it - on the fly - in to black and white? BTW: can i tell linux to swith the colors - in general - to black and white? is this doable... looks like we could write a small shell script, utilizing imagemagick. maybe like this: Code: for i in *jpg ; do mogrify -colorspace Gray "$i" ; done this is just a quick hack. i have tried. See more bleow: Also, it's not interactive and simply changes all jpg's to grayscale, even if they already are grayscale. please note that we need to have some more things about imagemagick. well see the results: martin@linux-70ce:~/Bilder> martin@linux-70ce:~/Bilder> for i in *jpg ; do mogrify -colorspace Gray "$i" ; done mogrify: unable to open image `*jpg': Datei oder Verzeichnis nicht gefunden @ error/blob.c/OpenBlob/2643. mogrify: no decode delegate for this image format `*jpg' @ error/constitute.c/ReadImage/552. martin@linux-70ce:~/Bilder> How can i edit just one image at on time with a multiple image upload form? I have the images being stored in a folder and the path being stored in MySQL. I also have the files being uploaded with a unique id. My issue is that I want to be able to pass the values of what is already in $name2 $name3 $name4 if I only want to edit $name1. I don't want to have to manually update the 4 images. Here is the PHP: Code: [Select] <?php require_once('storescripts/connect.php'); mysql_select_db($database_phpimage,$phpimage); $uploadDir = 'upload/'; if(isset($_POST['upload'])) { foreach ($_FILES as $file) { $fileName = $file['name']; $tmpName = $file['tmp_name']; $fileSize = $file['size']; $fileType = $file['type']; if ($fileName != ""){ $filePath = $uploadDir; $fileName = str_replace(" ", "_", $fileName); //Split the name into the base name and extension $pathInfo = pathinfo($fileName); $fileName_base = $pathInfo['fileName']; $fileName_ext = $pathInfo['extension']; //now we re-assemble the file name, sticking the output of uniqid into it //and keep doing this in a loop until we generate a name that //does not already exist (most likely we will get that first try) do { $fileName = $fileName_base . uniqid() . '.' . $fileName_ext; } while (file_exists($filePath.$fileName)); $file_names [] = $fileName; $result = move_uploaded_file($tmpName, $filePath.$fileName); } if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); $filePath = addslashes($filePath); } $fileinsert[] = $filePath; } } $mid = mysql_real_escape_string(trim($_POST['mid'])); $cat = mysql_real_escape_string(trim($_POST['cat'])); $item = mysql_real_escape_string(trim($_POST['item'])); $price = mysql_real_escape_string(trim($_POST['price'])); $about = mysql_real_escape_string(trim($_POST['about'])); $fields = array(); $values = array(); $updateVals = array(); for($i = 0; $i < 4; $i++) { $values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : ''; if($values[$i] != '') { $updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'"; } } $updateNames = ''; if(count($updateVals)) { $updateNames = ", " . implode(', ', $updateVals); } $update = "INSERT INTO image (mid, cid, item, price, about, name1, name2, name3, name4) VALUES ('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]') ON DUPLICATE KEY UPDATE cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames"; $result = mysql_query($update) or die (mysql_error()); The script for creating a new file name for the image:
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $new_image_name = md5(uniqid()) . "." . $ext[count($ext) - 1]; $target_path = $target_path . $new_image_name;//set the target path with a new name of imageThe script creates a new file like: f6c9b8d9db05366c3504210cded9ddb2.jpgand moves the file to the "uploads" folder. And then the script also creates a thumbnail with the same file name and moves the file to the "thumbs" folder. The issue I am having is that the same ID code could happen again for a different image in the database, thus I would be calling a different original sized image than the thumbnail image. My question is: How to avoid this issue of the same ID code has happened again for a different file. What is the proper way to reference the anchor tag of the thumbnail image to its actual original sized image? With the script I have the thumbnail image would be coming from the "thumbs" folder and the anchor tag would get referenced to the "uploads" folder to get the original sized image. Edited by glassfish, 12 October 2014 - 05:51 AM. After image is drop into container , I want to move copy of the original image to be move when original image dragend within container. I tried but it display copy image each time when original image dragend. can anyone help me?
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Prototype</title> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script> <style> body{padding:20px;} #container{ border:solid 1px #ccc; margin-top: 10px; width:350px; height:350px; } #toolbar{ width:350px; height:35px; border:solid 1px blue; } </style> <script> $(function(){ var $house=$("#house"); $house.hide(); var $stageContainer=$("#container"); var stageOffset=$stageContainer.offset(); var offsetX=stageOffset.left; var offsetY=stageOffset.top; var stage = new Kinetic.Stage({ container: 'container', width: 350, height: 350 }); var layer = new Kinetic.Layer(); stage.add(layer); var image1=new Image(); image1.onload=function(){ $house.show(); } image1.src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"; $house.draggable({ helper:'clone', }); $house.data("url","house.png"); // key-value pair $house.data("width","32"); // key-value pair $house.data("height","33"); // key-value pair $house.data("image",image1); // key-value pair $stageContainer.droppable({ drop:dragDrop, }); function dragDrop(e,ui){ var x=parseInt(ui.offset.left-offsetX); var y=parseInt(ui.offset.top-offsetY); var element=ui.draggable; var data=element.data("url"); var theImage=element.data("image"); var image = new Kinetic.Image({ name:data, x:x, y:y, image:theImage, draggable: true, dragBoundFunc: function(pos) { return { x: pos.x, y: this.getAbsolutePosition().y } } }); image.on("dragend", function(e) { var points = image.getPosition(); var image1 = new Kinetic.Image({ name: data, id: "imageantry", x: points.x+65, y: points.y, image: theImage, draggable: false }); layer.add(image1); layer.draw(); }); image.on('dblclick', function() { image.remove(); layer.draw(); }); layer.add(image); layer.draw(); } }); // end $(function(){}); </script> </head> <body> <div id="toolbar"> <img id="house" width=32 height=32 src="http://vignette1.wikia.nocookie.net/angrybirds/images/b/b6/Small.png/revision/latest?cb=20120501022157"><br> </div> <div id="container"></div> </body> </html> Edited by Biruntha, 08 January 2015 - 10:14 AM. Hi, I've read a lot of places that it's not recommended to store binary files in my db. So instead I'm supposed to upload the image to a directory, and store the link to that directory in database. First, how would I make a form that uploads the picture to the directory (And what kinda directories are we talking?). Secondly, how would I retrieve that link? And I guess I should rename the picture.. I'd appreciate any help, or a good tutorial (Haven't found any myself). Hello, I've had success creating a cool vanity QR code with rounded edges for my organization by generating a standard QR code, then applying a noise -> median effect in Photoshop to get the edges rounded among some other effects. Photoshop is great, but I want to automate this. I found a great PHP library to generate QR codes. The part I don't get is the rounding of the hard edges. I've seen other sites do it like this one. So far google searches are yielding rounded corner tutorials. Any thoughts on how to do this with GD or ImageMagic? Best regards, Chris Would like to be able to click on a radio button that represents an image. Once selected and submitted, have that image display on another page. I have an idea, but need some guidance. BTW, is using php only doable? Is there a simpler or more elegant way to do this? Thanks all! This topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=351137.0 |