PHP - Image Troubles
up until yesterday everything was fine, but now all of my icons are displaying at 10 times the size they originally are. This can only be fixed by defining width and height of them via css but i never had to do this before. Is this something to do with php? heres an eample line of code for an image i am using:
echo "<img src=\"{$site_root}/avatars/{$posts_info->user_avatar}\"/>"; any ideas why this is happening? that image is just an example btw. the same thing happens with icons that are 7x7. Similar TutorialsCan't figure out why this is not working for me... please help! Thanks <?php $gamertag = 'l RaH l'; $url = "http://api.xboxleaders.com/user_api.php?gamertag=".rawurlencode($gamertag); $output = file_get_contents($url); // try to convert the response into a PHP object $obj = json_decode($output); if(!is_object($obj)) die("Error parsing JSON response\n"); //define variables $avatar = ($obj->user->avatar); $gold = ($obj->user->gold); print $gold; print $avatar; ?> Here's what i've been attempting to do . a. I have a table "travelexpense" in 2 DBs. All columns are identical. b. Based on a set of parameters, a user can have a record in this table in one or both of the databases. c. When i want to output all the entries pertaining to that user in both these tables, I use Select Union. So far so good. d. However, the query references customers pertaining to those expenses . The customer table is present in both databases but is populated with different records. e. Now when the SELECT UNION runs, it picks up only the customer in the first database and not the second, even if there is an entry pertaining only to the second database. f. Odlly though the other data - that is the expenses themselves are selected correctly. Its only the customers entries that are wrong Code snippet below Code: [Select] $sqlZ= " SELECT * FROM $dbname2.`Travelexpense` WHERE Userid='$user' && MONTH(`Enddate`)=$month && YEAR(`Enddate`)=$year UNION select * from $dbname3.`Travelexpense` WHERE Userid='$user' && MONTH(`Enddate`)=$month && YEAR(`Enddate`)=$year "; $resultZ = mysql_query($sqlZ) or die (mysql_error()); $numofrows = mysql_num_rows($resultZ); for($i = 0; $i < $numofrows; $i++) { $myrowZ = mysql_fetch_array($resultZ); $coid = $myrowZ["CID"]; $s1 = "SELECT * FROM $dbname2.`Customers` WHERE `CID` = $coid UNION select * from $dbname3.`Customers` WHERE `CID` = $coid"; $result1 = mysql_query($s1); $myrow2 = mysql_fetch_array($result1); $Name=$myrow2["Company"]; //here's the problem . If say $coid = 150 , then it will look only at record 150 in Table Customers in dbname2 and NOT in Table Customers in dbname3 even if only dbname3 has a relevant entry. blah blah } Am i using UNION incorrectly esp in the query $s1? Appreciate any help . Thanks ! Swati I have this PHP file that I intend to provide the answers to only four questions in a little quiz in a "Questions" table: QuestionID, QuestionText Questions: 1 Which is NOT part of the FAT TOM acronym? 2 Of the following choices, which has a better chance of creating a foodborne illness? 3 How should food NEVER be thawed? 4 Where should pesticides be stored? The answers should go in the Answers table: "QuestionID, OptionText, CorrectAnswer" I have hundreds of questions and answers, but I need to get this small sample working first. The following code runs without triggering an error but it doesn't insert any data. <?php $link = mysql_connect('PathToMyData', 'myUsername', 'MyPassword'); // specifics removed for security if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('quiz'); $sql = "INSERT INTO ANSWERS (QuestionID,OptionText,CorrectAnswer) // CorrectAnswer is type BOOL (Correct=1 Wrong Answer=0) (VALUES (1,'food',0), (1,'alkalinity',1), (1,'time',0), (1,'temperature',0), (1,'oxygen',0), (1,'moisture',0), (2,'celery sticks',0), (2,'beef jerky',0), (2,'cranberry juice',0), (2,'baked potato',1), (2,'saltine cracker',0), (3,'in the refrigerator',0), (3,'in a pot in the kitchen at room temperator',1), (3,'as a part of the cooking process',0), (3,'under cool running water',0), (4,'close to the food preparation area for easy access',0), (4,'in a locked storage area away from food',1), (4,'in the dry storage area',0), (4,'in a bin or box under the sink',0);)"; $result = mysql_query($sql); // executes the query // close database mysql_close($link); ?> Then I go back to the MySQL admin area at my host's site and query up "SELECT * FROM Answers;" and nothing! It's still empty! As I said, no error was triggered, but nothing was inserted. This is discouraging.
I need to draw various font sizes onto a canvas to create a web service. Wanting to protect my HD assets, the intent is to use PHP to populate the image with the necessary text, and then scale down the image before presenting it to the user. <?php $img = imagecreatetruecolor(750, 530); $black = imagecolorallocate($img, 0, 0, 0); $gray = imagecolorallocate($img, 125, 125, 125); $white = imagecolorallocate($img, 255, 255, 255); $font = realpath('../fonts/micross.ttf'); $size = 12; $spacing = 20; for ($x = 0; $x <= 25; $x++) { $box = imageftbbox($size + $x/10, 0, $font, "The longer the phase the more apparent the size difference should be"); $boxWidth = $box[2] - $box[0]; imagefilledrectangle($img, 5, $x*$spacing+5, $boxWidth+5, ($x+1)*$spacing+5, $gray); imagefttext($img, $size + $x/10, 0, 5, $spacing*($x+1), $white, $font, "The longer the phase the more apparent the size difference should be Font Size ".($size+($x/10))); } imagejpeg($img); imagedestroy($img); ?> You can see how despite the font size steadily increasing by 0.1, it sporadically jumps at what seem at first like random intervals, however if you increase the number of loops and log the data, you can see that it alternates between increasing every 0.7, and 0.8. Unfortunately that doesn't help me any, just some insight. if($last != $boxWidth) { $last = $boxWidth; echo $boxWidth." ".($size+($x/10))."<br>"; }
This outputs the current width and font size each time the text width changes. Hey all, I'm am stumped. I'm working with someone else's code and I find they are using serialized arrays a lot. unfortunately at present I am not to familiar with serialized arrays and how to work with them and Ive been searching for an answer for a bit but I am not doing so hot in my quest, so I thought I'd come here and give it a crack. From what I gather the person that did this portion of the site I am working on pulled this as is from linkedin. From it I am trying to reconstruct it for the page I am putting into, this information is stored in hundreds of db entries so I cant really redo everything. Is there a direct way of working with this or do I have to covert it to an array or what is the best way to handle data like below, or serialized arrays in general for that matter. Example of what I am looking at: Code: [Select] {"@attributes":{"total":"1"},"position":{"id":"155477330","title":"Lead Architect","summary":{},"start-date":{"year":"2010","month":"10"},"is-current":"true","company":{"id":"209012","name":"Sprint Mobile Inc","type":"Privately Held","industry":"Internet"}}} And another example: Code: [Select] {"@attributes":{"total":"3"},"position":[{"id":"161998487","title":"Senior UX\/UI Designer","summary":"Plan, Design, and Direct User Experience Design\/Development. Also in charge of sharing and spreading the UX philosophy company-wide.","start-date":{"year":"2011","month":"1"},"is-current":"true","company":{"id":"209012","name":"UpMo","type":"Privately Held","industry":"Internet"}},{"id":"149276847","title":"Owner \/ Creative Director","summary":"I'm 27 years old and born and raised in Charleston, South Carolina. \n\nAs a web designer and developer with nearly 14 years of experience, I've always found myself to be interested in business development. I started my first web business when I was 17 years old and watched it grow from a one man operation in a bedroom, to twelve employees working from two office locations. \n\nOver the years I have developed over 200 websites and assisted in the design\/development in as many more.\n\nBeing an entrepreneur, I've developed a sixth sense for quality assurance on web projects -- in other words, if I cannot give it a thumbs up for my own business, why would I give it to you?","start-date":{"year":"2010","month":"6"},"is-current":"true","company":{"id":"1487228","name":"Brandon Rivers Consulting, LLC.","industry":"Internet"}},{"id":"71905623","title":"Chairman \/ Chief Executive Officer","summary":"Brandon is responsible for setting strategy and overseeing the day-to-day business and operations of Campus Rhythm.\n\nIn this position, Brandon\u2019s core responsibility is not only facilitating business outside of Campus Rhythm, but balancing internal and external initiatives to build a sustainable corporation. \n\nCampus Rhythm is the FIRST and ONLY fully automated Student to Student textbook network that allows students all over the country to set their own prices, and be connected to other students to buy and sell textbooks.","start-date":{"year":"2007","month":"10"},"is-current":"true","company":{"name":"Campus Rhythm, LLC.","industry":"Internet"}}]} Hello Community, good evening! i am having troubles with starting PHP on linux - [running OpenSuse-Linux] Could not open input file: - suse-linux:/usr/perl # php -v PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/extensions/readline.so' - libedit.so.0: cannot open shared object file: No such file or directory in Unknown on line 0 PHP 5.3.4-dev (cli) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies suse-linux:/usr/perl # well what is wrong here...? Hi all. I'm trying to build a dynamic multiple tiered navigation menu that operates on the existence of directories. So far, I have some code that will read through the document root, and one sub level of directories but I'm not sure how to get into the third level of directories. Here's what I have so far... The code: $docroot=scandir($_SERVER['DOCUMENT_ROOT']); unset($docroot[array_search('.',$docroot)]); unset($docroot[array_search('..',$docroot)]); unset($docroot[array_search('php',$docroot)]); unset($docroot[array_search('css',$docroot)]); unset($docroot[array_search('input_forms',$docroot)]); $docroot=array_values($docroot); //Build tier 1 echo "<div class=\"tier\">"; echo "<a href=\"/index.php\">Home</a>"; foreach($docroot as $value1){ if(is_dir($value1)){ $t2=scandir($_SERVER['DOCUMENT_ROOT'] . "/" . $value1); unset($t2[array_search('.',$t2)]); unset($t2[array_search('..',$t2)]); $t2=array_values($t2); $t1[]=$t2; echo "<a href=\"/$value1/\">"; $value1=str_replace("_"," ",$value1); $value1=ucwords($value1); echo $value1; echo "</a>"; } } echo "</div>"; The output: Code: [Select] [it automatically builds the first tier of the menu with some stylesheet definitions and places it here. I did this just for testing purposes.] Array ( [0] => Array ( [0] => bus_mgmt_context.pdf [1] => financial_management [2] => index.php [3] => nav.php [4] => service_level_management [5] => service_portfolio [6] => workforce_management ) [1] => Array ( [0] => element_inventory [1] => index.php [2] => mobile_administration [3] => monthly_bill_review [4] => nav.php ) [2] => Array ( [0] => business_it_requests [1] => change_management [2] => demand_management_context.pdf [3] => index.php [4] => nav.php [5] => project_management [6] => release_management ) [3] => Array ( [0] => availability_management [1] => capacity_management [2] => configuration_management [3] => index.php [4] => nav.php [5] => planning [6] => problem_management [7] => system_planning ) [4] => Array ( [0] => context [1] => input [2] => reports [3] => sop [4] => t3.php [5] => video ) [5] => Array ( [0] => executive_reports [1] => index.php [2] => kpi_index [3] => nav.php ) [6] => Array ( [0] => compliance [1] => hipaa_definitions.pdf [2] => index.php [3] => information_security [4] => nav.php [5] => risk_context.pdf [6] => service_continuity [7] => threat_management ) [7] => Array ( [0] => incident_management [1] => index.php [2] => nav.php [3] => release_management [4] => service_desk [5] => service_requests [6] => supplier_management ) ) 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. 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. 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). 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()); 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! Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. Hello, Five images will be displayed inside a division. There will be a previous and next button/link. If someone click the next button the next image will be added in that div and the first image will be gone from that div. The previous button/link will do the same thing. Is it possible with php? I am confused if it's a javascript or ajax question. Thanks. 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 Hello I am having problems uploading an image through a HTML form. I want the image to be uploaded to the server and the image name to be written to the mysql database. Below is the code I am using: Code: [Select] <?php if (isset($_POST['add'])){ echo "<br /> add value is true"; $name = $_POST['name']; $description = $_POST['description']; $price = $_POST['price']; $category_id = $_POST['category_name']; $image = $_FILES['image']['name']; //file path of the image upload $filepath = "../images/"; //mew name for the image upload $newimagename = $name; //new width for the image $newwidth = 100; //new height for the image $newheight = 100; include('../includes/image-upload.php'); mysql_query("INSERT INTO item (item_name, item_description, item_price, item_image) VALUES ('$name','$description','$price','$image')"); ?> Here is the image-upload.php file code: Code: [Select] <?php //assigns the file to the image $image =$_FILES["image"]["name"]; $uploadedfile =$_FILES["image"]["tmp_name"]; if ($image) { //retrieves the extension type from image upload $extension = getextension($image); //converts extension to lowercase $extension = strtolower($extension); //create image from uploaded file type if($extension=="jpg" || $extension=="jpeg") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); }else if($extension=="png") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefrompng($uploadedfile); }else{ $src = imagecreatefromgif($uploadedfile); } //creates a list of the width and height of the image list($width,$height)=getimagesize($uploadedfile); //adds color to the image $tmp = imagecreatetruecolor($newwidth,$newheight); //create image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); //set file name $filename = $filepath.$newimagename.".".$extension; $imagename = $newimagename.".".$extension; //uploads new file with name to the chosen directory imagejpeg($tmp,$filename,100); //empty variables imagedestroy($src); imagedestroy($tmp); } ?> Any help would be appreciated, fairly new to all this! Thanks!!! This topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=351137.0 I have a working image upload script that uploads, renames the file and adds filename to the database. is it possible to include some sort of image resize code? if so can anyone point me in the right direction or better still show some example code and explain how it works etc. below is my working code: Code: [Select] <?php $rand = mt_rand(1,9999999); $member_id = $_SESSION['SESS_MEMBER_ID']; $caption = $_POST["caption"]; if(isset($_FILES['uploaded']['name'])) { $allowed_filetypes = array('.jpg','.gif','.bmp','.png','.jpeg'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $errors = array(); $target = "gallery/"; $fileBaseName = substr($fileName, 0, strripos($fileName, '.')); // Get the extension from the filename. $ext = substr($fileName, strpos($fileName,'.'), strlen($fileName)-1); //$newFileName = md5($fileBaseName) . $ext; $newFileName = $target . $rand . "_" . $member_id.$ext; // Check if filename already exists if(file_exists("gallery/" . $newFileName)) { $errors[] = "The file you attempted to upload already exists, please try again."; } // Check if the filetype is allowed. if(!in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(!filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(!is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $newFileName)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //Lets INSERT database information here if(count($errors)==0) { $result = mysql_query("INSERT INTO `gallery` (`image`, `memberid`, `caption`) VALUES ('$newFileName', '$member_id', '$caption')") or die (mysql_error()); } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Image has been uploaded.<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br /><br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file:<br /><input class='text' name='uploaded' type='file' /><br />\n"; echo "Image Caption:<br /><input class='text' name='caption' type='text' value='' /><br /><br />\n"; echo "<input class='Button' type='submit' value='Upload' />\n"; echo "</form>\n"; } ?> Many thanks to phpfreaks again. I want to reduce a picture size from 600px * 500px to 60px * 50px size, then crop it become 50px *50px. I have two groups of codes, 1 is to reduce the size of image, other 1 is to crop the image. The problem is they works separately, how to combine this two groups of codes to make them work together? Below is my codes : Code: [Select] <?php //codes of group A - Reduce the size of image from 600px * 500px to 60px * 50px $save2 = "images/users/" . $image_name_2; //This is the new file you saving list($width2, $height2) = getimagesize($file) ; $modwidth2 = 50; $diff2 = $width2 / $modwidth2; $modheight2 = $height2 / $diff2; $tn2 = imagecreatetruecolor($modwidth2, $modheight2) ; $image2 = imagecreatefromjpeg($file) ; imagecopyresampled($tn2, $image2, 0, 0, 0, 0, $modwidth2, $modheight2, $width2, $height2) ; imagejpeg($tn2, $save2, 100) ; //codes of group B - Crop the image from 60px * 50px to 50px * 50px $save3 = "images/users/" . $image_name_3; list($width3, $height3) = getimagesize($file) ; $modwidth3 = 60; $diff3 = $width3 / $modwidth3; $modheight3 = $height3 / $diff3; $left = 0; $top = 0; $cropwidth = 50; //thumb size $cropheight = 50; $tn3 = imagecreatetruecolor($cropwidth, $cropheight) ; $image3 = imagecreatefromjpeg($file) ; imagecopyresampled($tn3, $image3, 0, 0, $left, $top, $cropwidth, $cropheight, $modwidth3, $modheight3) ; imagejpeg($tn3, $save3, 100) ; //save the cropped image ?> As you can see from 2 groups of codes above, 1st group resize the pic then save it to a folder. 2nd group of codes crop the pic then save it into the folder too. My question is ... After 1st group of codes resize the picture, is it necessary to save it into folder before I can crop it? If it is necessary, then I need to write new lines of codes to retrieve the resized pic from the folder for 2nd group of codes to crop it? If it is not necessary, after resizing the pic, how do I pass the pic to 2nd group of codes to crop it? php image-resizing Basically I want to open up a png file with a transparent background which is 48x48 pixels And set the opacity of this to about 50% of the original. I have the following to do what I want but just returns an empty image On imagecolorallocatealpha i have tried setting the alpha value at different values between 0 and 127 with no success as 127 returns a black block imagecopy($menu,$image, #Positioning 0,0, 0,0, #Image size 48,48 ); #Create transparent block $new_img = imagecreatetruecolor(48, 48); imagealphablending($new_img, true); $transparent = imagecolorallocatealpha($new_img, 255, 255, 255, 0); imagefilledrectangle($new_img, 0, 0, 48, 48, $transparent); #Put block over original image imagecopy($menu,$new_img, #Positioning 0,0, 0,0, #Image size 48,48 ); The image below shows on top the original and on bottom what I am roughly trying to create Where am i going wrong? |