How to resize an image on preview (no database) - javascript

I have script to preview input type=file (image), and generate it into pdf.
There's no problem for a small size of image. Then when i input with size 6Mb, the preview is OK, but when generate to pdf, its take very long time and finally stopped.
So, I want to resize the image size to 200x240px. But i don't know how to do it, because the script using javascript and I still newbie on it.
Please help how to resize it on my script.
Script:
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
console.log(reader.result);
//preview.src = reader.result;
$('#gen-template-frame').contents().find('.logo img').attr('src', reader.result);
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
HTML:
<!doctype html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../css/magang/front.css">
</head>
<body>
<div class="corpname" contenteditable>RUMAH SAKIT HARUM</div>
<div class="logosisma"><img src="https://sismadigroup.com/idcard/images/background/logo-id-card.png" width="219" height="70" /></div>
<div class="logo">
<!--<img src="resize/resize.php?src=https://sismadigroup.com/idcard/templates/images/avatar/3.jpg&scale=10&q=100">-->
<img src="https://sismadigroup.com/idcard/templates/images/avatar/3.jpg" width="200" height="240" />
</div>
<div class="name highlight" contenteditable>Maesyaroh</div>
<div class="position" contenteditable>Siswa Magang</div>
<div class="nik" contenteditable>SM-0035</div>
<div class="BBP">BENAR BAIK PANTAS</div>
<div class="BBPPoint" style="left:135px;"> . </div>
<div class="BBPPoint" style="left:203px;"> . </div>
</body>
</html>
Edit: PHP for PDF generation:
$frontPage = resolveDependency(stripslashes( $_POST[ "html" ] ));
$backPage = resolveDependency(stripslashes( $_POST[ "html2" ]) );
$frontPageCSS = getCSSFromHTML($frontPage);
$backPageCSS = getCSSFromHTML($backPage);
$mpdf = new mPDF('utf-8', array(75, 114.6), 0, '', 0, 0, 0, 0, 0, 0);
$mpdf->WriteHTML($frontPageCSS, 1);
$mpdf->WriteHTML($frontPage, 0);
$mpdf->WriteHTML('<pagebreak>', 2);
$mpdf->WriteHTML($backPageCSS, 1);
$mpdf->WriteHTML($backPage, 0);
$mpdf->Output('card.pdf', 'I');

Since you are using PHP to generate the PDF you can resize the image with PHP before using it with mPDF. I don't see in your code how you load the image, so I suppose that you use the Image() function for loading the image from a file (in this example $fileName is the name of the input image, replace it with the variable that you use in your code):
// $fileName is the name of the input image
list($width,$height)=getimagesize($fileName); // size of input image
$tempFileName=tempnam(sys_get_temp_dir(),"img").".png";
$newWidth=200;
$newHeight=240;
$image=imagecreatefrompng($fileName); // load the input image
$newImage=imagecreatetruecolor($newWidth,$newHeight); //create an empty image
imagecopyresampled($newImage,$image,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagepng($newImage,$tempFileName,9); // saving the new image to disk
// here you create the PDF using the image saved in $tempFileName
unlink($tempFileName); // and finally we delete the temporal file

I solved the same problem on front-end, before uploading file. You can visit a link!
import imageSqResizer from './image-square-resizer.js'
let resizer = new imageSqResizer(
'image-input',
300,
(dataUrl) =>
document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);
//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;

Related

How to display a pdf in the browser when uploading the pdf file

I'm working on a project and I want to display a pdf file as well as a text file in my web page
I did manage to display the contents of a text file.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(reader) {
return function() {
var contents = reader.result;
var lines = contents.split('\n');
document.getElementById('container').innerHTML = contents;
}
})(reader);
reader.readAsText(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" name="file" />
<div class="container">
<div class="backdrop">
<div class="highlights"></div>
</div>
<textarea id="container" style="height: 500px; min-width: 500px"></textarea>
</div>
I want to display both text files and PDF files, thanks for your help guys
You can use PDF.js which is community developed and supported by Mozilla Labs.
Looking at their example "Rendering the Page" is the golden ticket here.
I started off the example by breaking out 2 functions (1 to handle the text files and 1 to handle the PDF files) Take a look at the handlePDFFile function and you'll see its somewhat similar, a big difference is we read the file as reader.readAsDataURL(file); instead of reading it as text for the PDF.js library.
for PDF path you will still need to read the file and send the contents of the file to the pdfjsLib.getDocument function. After the loading promise is resolved you will be able to handle the pdf object.
with the pdf object we get the first page and render it onto our canvas. This is only an example so you will need to build on this if you wanted to view multiple pages (only the first page is hard coded).
const PDF_TYPE = "application/pdf";
const TXT_TYPE = "text/plain";
document.getElementById('files').addEventListener('change', handleFileSelect, false);
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
let fileType = files[i].type;
if (fileType === PDF_TYPE) {
handlePDFFile(files[i]);
} else if (fileType === TXT_TYPE) {
handleTxtFile(files[i])
} else {
console.error(`cannot handle file type: ${fileType}`)
}
}
}
function handleTxtFile(file) {
var reader = new FileReader();
reader.onload = (function(reader) {
return function() {
var contents = reader.result;
var lines = contents.split('\n');
document.getElementById('container').innerHTML = contents;
}
})(reader);
reader.readAsText(file);
}
function handlePDFFile(file) {
var reader = new FileReader();
reader.onload = (function(reader) {
return function() {
var contents = reader.result;
var loadingTask = pdfjsLib.getDocument(contents);
loadingTask.promise.then(function(pdf) {
pdf.getPage(1).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport({
scale: scale,
});
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
});
}
})(reader);
reader.readAsDataURL(file);
}
#the-canvas {
outline: black 3px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.min.js"></script>
<input type="file" id="files" name="file" />
<div class="container">
<div class="backdrop">
<div class="highlights">
</div>
</div>
<textarea id="container" style="height: 200px; min-width: 200px"></textarea>
<canvas id="the-canvas"></canvas>
</div>
FOR PDF
Upload your PDF file in Google drive and use its URL in a iframe(like Google Drive) and use its URL in a iframe
<object data="data/test.pdf" type="application/pdf" width="500" height="300">
file.pdf
</object>
Also see this link:-How to Use pdf.js

Upload Image Preview code created by Button doesn't preview the image. Javascript/HTML

So basically i'm stuck. I created a simple upload image button that allows me to preview the image file that i uploaded. I also created a button that creates another upload image button the button is called "Try It". My first upload image button, previews the image correctly, but when i push the "Try It" to create another upload image button and upload another image, it does not preview on the additional upload image button. I just want to know how i can fix it. Below is the full code:
function myFunction() {
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= "previewFile()";
document.getElementById("wtf").appendChild(x);
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
document.getElementById("preview").appendChild(y);
}
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile()">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>
First of all element.onchange takes a function and not a string i changed that also since you need to show different previews with different buttons you need a way to distinguish between them. I am creating a global variable i to keep track of it and passing it to the previewFile function as a parameter.
Here is the code:
var i = 0;
function previewFile(index){
var preview = document.querySelectorAll('img'); //selects the query named img
var file = document.querySelectorAll('input[type=file]')[index].files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview[index].src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
function myFunction() {
i++;
var y = document.createElement('IMG');
y.src= "";
y.alt= "Image preview...";
y.height = 200;
document.getElementById("preview").appendChild(y);
var x = document.createElement("INPUT");
x.type = "file";
x.id= "file-upload"
x.onchange= function(){previewFile(i)};
document.getElementById("wtf").appendChild(x);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to create a File Upload Button.</p>
<button onclick="myFunction()">Try it</button>
<p id="wtf">
<input id="file-upload" type="file" onchange="previewFile(0)">
</p>
<p id="preview">
<img src="" height="200" alt="Image preview...">
</p>
</body>
</html>

File reader Javascript

currently i am choosing a file and converting to base64 string and displaying in html page.see the below code.
But i want in such a way that while loading the function it will automatically fetch the file from the location where the image saved and convert to base64 and display. I just want to skip the manual way of choosing..please help
<html>
<body>
Choose File: <input id="imageToLoad" type="file" onchange="displayImage();" />
<p>Image encoded</p>
<textarea id="base64TextArea" style="width:550;height:240" ></textarea>
<img id="myImg" width="218" height="300" src="" />
<script type="text/javascript">
function displayImage()
{
var filesSelected = document.getElementById("imageToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
base64TextArea.innerHTML = fileLoadedEvent.target.result;
document.getElementById("myImg").src = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
</body>
</html>
You can't fetch arbitrary files on a client's computer with JS. Using most browsers, the client must manually choose a file to be processed by the script.
If you think about it, it would be a major security flaw if any website could access any file on your computer.
I'm not sure why Base64 is an important aspect here. Please give some details if converting the image to text is a specific requirement of your needs, but if you only want to display and reference the image, you can start with this:
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
document.getElementById("myImg").src = URL.createObjectURL(fileToLoad);
}
This will use an "object URL" which is a shorthand way of referring to a file that has been drag/dropped, or picked from an <input>

Resize and upload files without AJAX

Edit
It seems that this is most likely not possible because the canvas and the file input are not compatible data types.
The way to do something similar is to send an AJAX request using a "data url". I will look into that in more detail. Since I didn't want to use AJAX I'll try to fake the workflow to be more like a normal submit, i.e. with a refresh at the end.
End edit
I want to resize and upload a file without AJAX, as this is how it is currently being done (without a resized image - taken from a phone/tablet) and it works well in terms of workflow.
Hence after doing a resize I want to be able to make the resized "image" the value of a field, if this is possible.
I am using this library http://gokercebeci.com/dev/canvasresize to do the resizing for me.
I tried setting the data variable in the callback to be the file1 input's value i.e.
$("#file1").val(data);
But this threw an error. I have removed it in the code below, since I was pretty sure that wasn't the way to go about it.
I've copied the entire HTML/JS file below (the "Image Uploading" content was an example of using AJAX to upload the image, I have commented it out because I don't want to do that).
<!DOCTYPE html>
<html>
<head>
<title>Resize and Upload Images</title>
<script type="text/javascript" src="/public/javascripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/public/javascripts/zepto.min.js"></script>
<script type="text/javascript" src="/public/javascripts/jquery.exif.js"></script>
<script type="text/javascript" src="/public/javascripts/jquery.canvasResize.js"></script>
<script type="text/javascript" src="/public/javascripts/binaryajax.js"></script>
<script type="text/javascript" src="/public/javascripts/canvasResize.js"></script>
<script type="text/javascript" src="/public/javascripts/exif.js"></script>
</head>
<body style="margin:48px;">
<div id="devcontainer">
<div id="area">
<h3>canvasResize</h3>
<div>
<form action="/upload" enctype="multipart/form-data" method="POST">
<input name="file1" type="file" id="file1"/>
<input name="file1" type="file"/>
<input name="data1" type="text"/>
<input name="data2" type="text"/>
</form>
<p><span></span></p>
<i></i>
</div>
<script>
$().ready(function() {
$('input[name=file1]').change(function(e) {
var file = e.target.files[0];
// RESET
$('#area p span').css('width', 0 + "%").html('');
$('#area img, #area canvas').remove();
$('#area i').html(JSON.stringify(e.target.files[0]).replace(/,/g, ", <br/>"));
// CANVAS RESIZING
canvasResize(file, {
width: 600,
height: 0,
crop: false,
quality: 80,
callback: function(data, width, height) {
// SHOW AS AN IMAGE
// =================================================
var img = new Image();
img.onload = function() {
$(this).css({
'margin': '10px auto',
'width': width,
'height': height
}).appendTo('#area div');
};
// /SHOW AS AN IMAGE
// =================================================
$(img).attr('src', data);
}
});
});
});
</script>
</div>
<div class="clearfix"></div>
</div>
</body>
</html>
<!--
// IMAGE UPLOADING
// =================================================
// Create a new formdata
var fd = new FormData();
// Add file data
var f = canvasResize('dataURLtoBlob', data);
f.name = file.name;
fd.append($('#area input').attr('name'), f);
var xhr = new XMLHttpRequest();
var loaded = Math.ceil((e.loaded / e.total) * 100);
$('#area p span').css({'width': loaded + "%"}).html(loaded + "%");
}
}, false);
// File uploaded
xhr.addEventListener("load", function(e)
{
var response = JSON.parse(e.target.responseText);
if (response.filename)
{
// Complete
$('#area p span').html('done');
$('#area b').html(response.filename);
$('<img>').attr({
'src': response.filename
}).appendTo($('#area div'));
}
}, false);
// Send data
xhr.send(fd);
}
-->
Create a callback function in the main window. Add an iFrame to the page that will handle file upload. Once your files have been uploaded call the call back function with the file names. Add the files to the canvas.

how can i get the height and width of image without page refresh in file tag? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
get image height and width in file tag using javascript
how can i get the height and width of image without page refresh in file tag?
<HTML>
<HEAD>
<TITLE></TITLE>
<script language="javascript">
function getW(){
var theImg = document.getElementById('testimg');
alert(theImg.width);
}
function getH(){
var theImg = document.getElementById('testimg');
alert(theImg.height);
}
</script>
</HEAD>
<BODY>
<input type="file" id="testimg"/>
<input type="button" value="get Width" onclick="getW()"/>
<input type="button" value="get Height" onclick="getH()"/>
</BODY>
</HTML>
i get the image height and width of image using php code, but that time page will be refreshed, without page refresh i get image size but not a height and width....
You can upload file through iframe and after iframe reloaded get image width/height. In modern browsers you can use FileReader API:
<input type="file" id="files" multiple/>
<script type="text/javascript">
function handleFileSelect() {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', theFile.name, '"/>'].join('');
document.body.appendChild(span);
var img = span.getElementsById('img');
img.onload = function() {
alert(img.src, img.offsetWidth, img.offsetHeight);
document.body.removeChild(span);
}
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
There is an excellent post about reading file in javascript.

Categories