Save cropped image to local server and it URL to MySQL database - php

I am using cropit to crop image.
<body>
<div class="image-editor">
<input type="file" class="cropit-image-input">
<!-- .cropit-image-preview-container is needed for background image to work -->
<div class="cropit-image-preview-container">
<div class="cropit-image-preview"></div>
</div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<button class="export">Save</button>
</div>
<script>
$(function() {
$('.image-editor').cropit({
exportZoom: 1.25,
imageBackground: true,
imageBackgroundBorderWidth: 10,
imageState: {
src: '../image/default-avatar.png'
}
});
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
window.open(imageData);
});
});
</script>
</body>
I have faced two issues:
When i do the cropping and clicking on save button cropped image opens in new window. I want that it should not open in new window, instead cropped image should save to related user folder like:
ROOT_PATH.'user/upload/'.$row['UserName'].'/avatar/big/'
I want to also save the latest cropped image URL to be saved in MySQL database in AvatarImage column.
Beneath find MySQL database information:
Database name: ara
Database user: root
Database password:
Database address: 127.0.0.1

you must encode base64 image file using php, and save your image to a file directory,
please try to trick existing like this link
How to create and save image to a website folder from a base64 encoded data/string using PHP

Related

jQuery image upload with dynamic loading

I have a single image form I would like to upload my images with for a store page. It simply needs to be clicked, show the upload box, and then autoSubmit when they select the image and replace the one image with the new uploaded item.
Here is the current page layout, with no actual upload button. On image click, we will show the upload windows on users PC:
This is the code for the highlighted area in the HTML field
<div class="uploader">
<form method="POST" id="upload_image">
<img src="/img/upload.png" id="imageUpload" alt="upload" />
</form>
</div>
So once the form submits, using an Ajax request, when it returns and is successful I plan to store the image name (usually the current time() as filename) as a session variable, now I need to show a Loading... image while the upload process happens and then replace the imageUpload with the new image located in /img/thumbs/NEWIMAGENAMEHERE.png.
Question Time
Is there a jQuery function that I can use to replace the image with the loading image and then the loaded image once upload completes? Is there a jquery library already for SINGLE image upload like this? all the library's I have found work for multiple images and since we only support one image on this store layout, we don't want multiple image upload.
Thanks
Thanks to suggestion from #aron9forever I have decided instead of upload the image right away on it's own, I would simply display the image and then upload on form submit. This does pose the annoying issue that when they submit the form, if there is an issue, that they need to re-click upload image but I may have a way around that using $_POST variables.
<div class="uploader">
<img id="imagetoUpload" src="/com/img/upload.png" alt="upload">
</div>
<input type="file" id="productImage" style="display:none;" name="img" value="">
Using this jQuery
$(function() {
function readURL(input) {
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagetoUpload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
};
$("#productImage").change(function(){
readURL(this);
});
$("#imagetoUpload").click(function() {
$("input[id='productImage']").click();
});
});

How to upload an image to server on change

I have an input tag like
<form id="myForm">
<!-- has lots of inputs above like username password etc -->
<input type="file" id="user_photo" name="user_photo" tabindex="6" size="6" class="" accept="jpeg|png|jpg|gif|PNG|JPEG|GIF|JPG" >
OnChange, I would want to upload an image through AJAX and save it in server. After saving, it should display in a preview div where I can use jCrop to crop as user wishes and save it again to the server (after cropping) when user clicks submit button.
If you have a better method please tell me.
inshort, I just want to trigger an ajax post request with the file contents and save it into my uploads folder without sending the rest of the form elements.
I use codeigniter. I have tried fileuploader by valum.. didnt give me the result.
Answer was stolen from here: Can i preview the image file who uploaded by user in the browser?
Use the HTML5 File Api to load the image client side.
Then use jCrop at the after loading the image into a tag.
Then (I'm assuming) use jCrops onRelease method to do the Ajax call.
That way its only one ajax call, and its already modified
<img id="preview" src="placeholder.png" height="100px" width="100px" />
<input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
<script type="text/javascript">
function previewImage(input) {
var preview = document.getElementById('preview');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
preview.setAttribute('src', e.target.result);
$('#preview').Jcrop({
onRelease: yourAjaxFunctionToSubmitToServer
});
}
reader.readAsDataURL(input.files[0]);
} else {
preview.setAttribute('src', 'placeholder.png');
}
}
</script>
Obviously this will need to be modified a bit to suit your needs, but you get the idea.

How do I convert my entire div data into image and save it into directory without using canvas?

i have already created my data (template-containing image,text,label etc) inside div now i want to convert it into image format. is there any technique to convert a specific div content into images without using canvas.anybody plz help me !
i want to convert entire "mydiv" content into image and save that image into my image directory, when i click on save ?
<html>
<header>
</header>
<body>
<label> Template Design</label>
<div id="mydiv">
<label> Good Morning</label>
<img src="mug.png" id="img1" height="100" width="100" />
</div>
<input name="save" type="button" value="SAVE" />
</body>
</html>
UPDATE (March 2018): Hello people of the future! This answer still gets a lot of traffic and I noticed that the old JSFiddle I'd put together was broken so it's been updated. New JSFiddle showing this technique is here: https://jsfiddle.net/Sq7hg/1913.
--
You might want to look into a Flash-based solution if you can't use <canvas> (though unless this specifically needs to work in old versions of IE I'm not sure why you can't).
http://flashcanvas.net/ is an emulation of <canvas> using Flash that might get you where you need to go. The documentation says that it supports toDataURL() so that might work for you.
Can you provide more insight into what your restrictions around <canvas> are and what you've attempted to try already?
//EDIT
According to your comment below you might be able to use <canvas>, in which case you can try using http://html2canvas.hertzen.com – it's a JavaScript solution that basically re-writes the DOM of a specified part of your code to a <canvas> and then allows you to interact with it however you want, including turning it into image data via toDataURL().
I've not used it before, but your JavaScript code would look something like this:
html2canvas([document.getElementById('mydiv')], {
onrendered: function(canvas) {
var data = canvas.toDataURL('image/png');
// AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server
}
});
I've knocked together a quick jsfiddle of this in action here: https://jsfiddle.net/Sq7hg/1913/ (note: updated link as per above)
This jsfiddle shows how to use the toDataURL() method to convert the canvas to an image and append it to the document. Saving the generated image to a server is an infinitely more complex task as it will require an AJAX call or somesuch to send the image data to a PHP script that converts the generated data: URL to an actual image and then saves it to a directory that you have permission to write to. If that's what you need to do, rather than going into that here I'd recommend starting with this Stack Overflow question: How to save an HTML5 Canvas as an image on a server?
This works perfectly...must be the simplest solution .
//html
<div id="mydiv" style="background-image:url(Koala.jpg) ;background-size: 100%;
background-size :200px 200px;
background-repeat: no-repeat;">
<p>text!</p>
<img src="mug.png" height="100" width="100"/></div>
<div id="canvas">
<p>Canvas:</p>
</div>
<div style="width:200px; float:left" id="image">
<p style="float:left">Image: </p>
</div>
<div style="float:left;margin-top: 120px;" class="return-data">
</div>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
//Style
#mydiv {
background-color: lightblue;
width: 200px;
height: 200px
}
//Script
<script language="javascript">
html2canvas([document.getElementById('mydiv')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
//display 64bit imag
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
// AJAX call to send `data` to a PHP file that creates an PNG image from the dataURI string and saves it to a directory on the server
var file= dataURLtoBlob(data);
// Create new form data
var fd = new FormData();
fd.append("imageNameHere", file);
$.ajax({
url: "uploadFile.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
}).done(function(respond){
$(".return-data").html("Uploaded Canvas image link: "+respond+"").hide().fadeIn("fast");
});
}
});
function dataURLtoBlob(dataURL) {
// Decode the dataURL
var binary = atob(dataURL.split(',')[1]);
// Create 8-bit unsigned array
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
// Return our Blob object
return new Blob([new Uint8Array(array)], {type: 'image/png'});
}
</script>
here is a sample demo

How to upload image with Jasny's bootstrap imagepreview?

I'm trying to use Jasny's Bootstrap. This is nice work!
I coudn't find solution for bootstrap upload image on page http://jasny.github.com/bootstrap/javascript.html#fileupload
With bootstrap-fileupload.js, how can I upload image using Ajax?
I asked this question to directly ARNOLD DANIELS who is owner of Jasny's Bootstrap.
Here is his answer:
The whole point of the image preview is that the picture is show right
away, without the need to upload it to the server using AJAX. So it
stays just a regular form. You can post a form using AJAX
http://api.jquery.com/jQuery.post/ if needed.
If you do want to upload the image using AJAX and don't want to use a
form, checkout
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
I used this sample with removing database releated lines and worked perfectly for me !
First you need to register the css and js files:
If you are using Yii Framework:
$cs = Yii::app()->clientScript;
$cs->registerCSSFile("/css/fileupload.css");
$cs->registerScriptFile('/js/fileupload.js', CClientScript::POS_END);
Or
<link rel="stylesheet" type="text/css" href="/css/fileupload.css">
<script type="text/javascript" src="/js/fileupload.js"></script>
Then register the following script:
$cs->registerScript("imageUpload", "$('.fileupload').fileupload({uploadtype: 'image'});", CClientScript::POS_END) ;
Or
<script type="text/javascript">
$('.fileupload').fileupload({uploadtype: 'image'});
</script>
Then add the following HTML code to your page:
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-preview thumbnail" style="width: 200px; height: 150px;"></div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
Remove
</div>
</div>
I came across this question on Google and just wanted to show I did it for anyone else interested (even if it's not the most elegant way)
$(document).ready(function(){
$('.fileinput-preview').bind('DOMNodeInserted', function(event) {
var imgdata = ($('.fileinput-preview img').attr('src'));
$.post( "upload.php", { imgdata: imgdata})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
})
})
This above piece of code detects when the file input preview has changed. It then finds the base64 data from the image tag, and uses jquery to post it to upload.php.
Upload.php simply takes the base64 image data and saves it as an image
$imgdata = $_POST['imgdata'];
$ifp = fopen("newimage.jpg", "wb");
$data = explode(',', $imgdata);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
The upload on jasny is more than a preview or client side upload management instead an ajax, probably you need tp use other method or plugin, cause the jasny upload will send the preview path using the binary image displaying

jquery faking an ajax request

To make a nicer experience of a file upload, I am faking an ajax request i.e The user clicks submit, the form dissapears a loading graphic appears and after a view seconds the page refreshs to show their newley upload image.
However since adding the jquery in my file upload always returns the same errors,
You did not select a file to upload. Why is this? This is my form,
<div id="picture_upload">
<div class="loading"></div>
<?php echo form_open_multipart('my_profile/do_upload'); ?>
<strong>Choose pictures to upload</strong>
<p>Max file size: 1MB .jpeg, .gif, .png or .bmp</p>
<input type="file" name="userfile" />
</div>
<!--<div id="webcam_upload">
<p>Hello</p>
</div>-->
</div>
<div id="bottom"><table><tr><td><input type="submit" id="submit_upload" value="Upload a picture" class="button green rounded_5 small" /></td><td>or</td><td><a href="#" id="close_modal" />Cancel</a></td></tr></table></div>
and my js,
$("#submit_upload").click(function(e){
//alert("here");
setTimeout(function() { $("#picture_upload form").submit();}, 6000);
$("#picture_upload").children().hide();
$(".loading").show();
setTimeout( function() { location=$("#picture_upload form").attr('action') }, 1500 );
return false;
});
The upload function is just your basic upload function from codeigniter.
For security reasons You can't upload a file using an XmlHttpRequest object (AJAX).
Alternative solutions are:
Load your file submission form in an iframe and post that with JS
Use a flash file uploader
Use HTML5
Here's a jQuery plugin that appears quite popular: http://www.uploadify.com/
Try like this,
$("#submit_upload").click(function(e){
//alert("here");
setTimeout(function() { $("#picture_upload form").submit();}, 6000);
$("#picture_upload").children().hide();
$(".loading").show();
return false;
});
And then redirect/reload the page using php
header('Location: URL_TO_REDIRECT'); //put it in your end of upload script in php file
If you don't want to redirect from PHP then, you can use
jQuery Form plugin http://jquery.malsup.com/form/#file-upload
SWFUpload http://demo.swfupload.org/v220/index.htm
(there are many libraries for uploading file.)
If you want to learn how to build your own upload using jQuery here is a good article - http://www.peachpit.com/articles/article.aspx?p=1766159

Categories