How to upload image directly from file upload button in javascript - javascript

Below is my script which was working fine.
But right now my image url was static at bottom of the script,
But i want to make it dynamic using file upload button.
Means if i select a file from upload button, then it will preview both images.
Below is the line
img.src = "https://image.ibb.co/bGtv0z/Product_Two.jpg";
where my image was fixed. i want to get this URL from file upload button.
Please help me to make it dynamic.
var img = new Image(),
$canvas = $("<canvas>"),
canvas = $canvas[0],
context;
var removeBlanks = function(imgWidth, imgHeight) {
var imageData = context.getImageData(0, 0, imgWidth, imgHeight),
data = imageData.data,
getRBG = function(x, y) {
var offset = imgWidth * y + x;
return {
red: data[offset * 4],
green: data[offset * 4 + 1],
blue: data[offset * 4 + 2],
opacity: data[offset * 4 + 3]
};
},
isWhite = function(rgb) {
// many images contain noise, as the white is not a pure #fff white
return rgb.red > 242 && rgb.green > 240 && rgb.blue > 240;
},
scanY = function(fromTop) {
var offset = fromTop ? 1 : -1;
// loop through each row
for (var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {
// loop through each column
for (var x = 0; x < imgWidth; x++) {
var rgb = getRBG(x, y);
if (!isWhite(rgb)) {
return y;
}
}
}
return null; // all image is white
},
scanX = function(fromLeft) {
var offset = fromLeft ? 1 : -1;
// loop through each column
for (var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {
// loop through each row
for (var y = 0; y < imgHeight; y++) {
var rgb = getRBG(x, y);
if (!isWhite(rgb)) {
return x;
}
}
}
return null; // all image is white
};
var cropTop = scanY(true),
cropBottom = scanY(false),
cropLeft = scanX(true),
cropRight = scanX(false),
cropWidth = cropRight - cropLeft,
cropHeight = cropBottom - cropTop;
var $croppedCanvas = $("<canvas>").attr({
width: cropWidth,
height: cropHeight
});
// finally crop the guy
$croppedCanvas[0].getContext("2d").drawImage(canvas,
cropLeft, cropTop, cropWidth, cropHeight,
0, 0, cropWidth, cropHeight);
$("#oldimg").
append("<p>same image with white spaces cropped:</p>").
append($croppedCanvas);
console.log(cropTop, cropBottom, cropLeft, cropRight);
};
img.crossOrigin = "anonymous";
img.onload = function() {
$canvas.attr({
width: this.width,
height: this.height
});
context = canvas.getContext("2d");
if (context) {
context.drawImage(this, 0, 0);
$("#newimg").append("<p>original image:</p>").append($canvas);
removeBlanks(this.width, this.height);
} else {
alert('Get a real browser!');
}
};
// define here an image from your domain
img.src = "https://image.ibb.co/bGtv0z/Product_Two.jpg";
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<body style="background-color:#ddd">
<input type="file" src="">
<div id="oldimg"></div>
<div id="newimg"></div>
</body>

When you choose a file in file input it is only in temporary memory and not on a server. Thus you will be unable to display it.
In order to do to what you want, you can either add a form that uploads the file and after file upload you can display it or use a FileReader. But this question was already answered, so please before asking a question try to find the solution by your own first.
Here is an answer with FileReader

Related

Tumblr API Jquery load image

I'd like to use the tumblr API with JS to draw the latest posted images to blog with mouse movement.
I've successfully got it drawing HTML image links but need some help implementing the API images.
I've made a JSfiddle - I'm looking to replace the two tree images with the API loaded images, the aim is to have all of the API images (20) to draw on with the mouse movement. In the fiddle I have loaded the API images onto the page to check they are being received properly.
https://jsfiddle.net/Hevering123/xpvt214o/721906/
// Tumblr API load -
$.ajax({
url: "https://api.tumblr.com/v2/blog/typophile.tumblr.com/posts?api_key=sNCvOfqUTzUJzBOViCbYfkaGeQaFAS4Q4XNtHMu8YPo6No3OiY",
dataType: 'jsonp',
success: function(posts){
var postings = posts.response.posts;
var text = '';
for (var i in postings) {
var p = postings[i];
var type = p.type;
if(type == 'photo'){
text += '<li><img src=' + p.photos[0].original_size.url +'></li>';
}else if(type == 'text'){
text += '<li>' +p.body+ '</li>';
}else{
text += '<li>Some other post type<li>';
}
console.log(type);
}
$('ul').append(text);
}
});
Below is the draw image JS
// draw image function
function resizeCanvas() {
canvas.width = window.innerWidth,
canvas.height = window.innerHeight,
drawStuff()
}
function drawStuff() {
function e() {
new Date - a < p ? setTimeout(e, p) : (g = !1,
context.clearRect(0, 0, canvas.width, canvas.height))
}
// It's the below code specifically that I'm completely stuck with, how do I replace the local img pngs with the correct JS to call in the API tumblr images
var i = ["https://www.fast-growing-trees.com/images/P/Sawtooth-Oak_450_a.jpg", "https://cdn.allbirds.com/image/fetch/q_auto,f_auto/q_auto,f_auto,b_rgb:fff,w_500/https://cdn.shopify.com/s/files/1/1104/4168/files/PDP_Plant_1_1.png%3Fv%3D1520805044" ]
, t = {
x: 0,
y: 0
}
, n = 80
, _ = 0;
isMobile && (n = 1);
var a, g = !1, p = 2500;
jQuery("#bg-canvas").on("mousemove touchend", function(s) {
if (jQuery(".move").hide(),
a = new Date,
g === !1 && (g = !0,
setTimeout(e, p)),
s.pageX - t.x > n || s.pageX - t.x < -n || s.pageY - t.y > n || s.pageY - t.y < -n) {
t.x = s.pageX,
t.y = s.pageY;
var o = new Image;
o.onload = function() {
var e = .5 * this.width
, i = .5 * this.height;
context.drawImage(o, s.pageX - e, s.pageY - i)
}
,
_ < i.length - 1 ? (_++,
o.src = i[_]) : (_ = 0,
o.src = i[_])
}
}),
jQuery("header p")({
})
}
var MD = [].join("\n");
console.log(MD, "color: white; background-color: black;");
var isMobile = !1;
"ontouchstart"in document.documentElement && (jQuery(".move").text("tap"),
isMobile = !0);
var canvas = document.getElementById("bg-canvas")
, context = canvas.getContext("2d");
window.addEventListener("resize", resizeCanvas, !1),
resizeCanvas();
Any help is very appreciated!

Pepper: strange image from camera

I want to show an image in the tablet of Pepper from his camera. I have done the Javascript code to process and show the image in a web view. The problem is that the image showed is strange:
I have written this code based on this example:
var CAMERA_ID = 'fger';
QiSession(function (session) {
session.service('ALMemory').then(function (ALMemory) {
// Listener to Choregraphe APP
ALMemory.subscriber('PepperQiMessaging/totablet').then(function(subscriber) {
subscriber.signal.connect(toTabletHandler);
});
// Says to Choregraphe that I'm listening with the id QR
ALMemory.raiseEvent('PepperQiMessaging/fromTabletResponse', 'QR');
// Video receiver function
session.service('ALVideoDevice').then(playVideo);
});
});
// This is the important part
function playVideo(video) {
video.subscribeCamera(
CAMERA_ID,
0, // cameraId kTop kBottom kInfred(color:17)
1, // Image of 640*480px
11, //RGB
10 // framerate 1~30
).then(function(result){
video.getImageRemote(result).then(function(image) {
if (image) {
var canvas = $('canvas')[0].getContext('2d');
var width = image[0];
var height = image[1];
var nb = image[2];
var imageData = image[6];
var read = 0;
var img = canvas.createImageData(width, height);
var pixs = img.data;
var binary = window.btoa(imageData);
var len = imageData.length;
var m = len/nb;
// Transformations to get the image in RGB
for (var i = 0; i < m; i++) {
pixs[i*4] = binary.charCodeAt(i*nb);
pixs[i*4+1] = binary.charCodeAt(i*nb+1);
pixs[i*4+2] = binary.charCodeAt(i*nb+2);
pixs[i*4+3] = 255;
}
canvas.putImageData(img, 0, 0);
}
video.unsubscribe(CAMERA_ID);
});
});
}
What I have to do to solve this problem?
At the end I found the solution. I found another example that it worked for me (the image is greyscale).
This is the algorithm to transform the bytes received form the camera to an image:
function getImage(ALVideoDevice, subscriberId) {
ALVideoDevice.getImageRemote(subscriberId).then(function (image) {
if(image) {
var imageWidth = image[0];
var imageHeight = image[1];
var imageBuf = image[6];
if (!context) {
context = document.getElementById('canvas').getContext('2d');
}
if (!imgData || imageWidth != imgData.width || imageHeight != imgData.height) {
imgData = context.createImageData(imageWidth, imageHeight);
}
var data = imgData.data;
for (var i = 0, len = imageHeight * imageWidth; i < len; i++) {
var v = imageBuf[i];
data[i * 4 + 0] = v;
data[i * 4 + 1] = v;
data[i * 4 + 2] = v;
data[i * 4 + 3] = 255;
}
context.putImageData(imgData, 0, 0);
}
if(previewRunning) {
setTimeout(function() { getImage(ALVideoDevice, subscriberId) }, 100);
}
});
}
Here is the complete Choregraphe project and the complete code.

How to do image resize with Javascript canvas

I am trying to resize my image with javascript.
First, I place the image on the canvas, so I can manipulate it.
I can make it smaller but the problem is I can't make it bigger with Scale transformation. To make it easy, I will insert my code here
<!DOCTYPE HTML>
<html>
<body>
<canvas id='canvas1'></canvas>
<hr>
<button id='read'>READ IMAGE</button>
<hr>
Scale <input type='range' value='1' min='0.25' max='2' step='0.25' id='scale'>
<br><button id='default2'>Default Scalling</button>
<hr/>
</body>
<script src='imagine.js'></script>
<script>
var canvas = document.getElementById('canvas1')
var obj = new pc(canvas)
obj.image2canvas("565043_553561101348179_1714194038_a.jpg")
var tes = new Array()
document.getElementById('read').addEventListener('click',function(){
tes = obj.image2read()
})
document.getElementById('scale').addEventListener('change',function(){
var scaleval = this.value
var xpos = 0
var ypos = 0
var xnow = 0
var ynow = 0
var objW = obj.width
var objH = obj.height
tesbackup = new Array()
for(var c=0; c<tes.length; c++){
temp = new Array()
for(var d=0; d<4; d++){
temp.push(255)
}
tesbackup.push(temp)
}
for(var i=0; i<tes.length; i++){
xpos = obj.i2x(i)
ypos = obj.i2y(i)
xnow = Math.round( (xpos)*(scaleval))
ynow = Math.round( (ypos)*(scaleval))
var idxnow = obj.xy2i(xnow,ynow)
tesbackup[idxnow][0] = tes[i][0]
tesbackup[idxnow][1] = tes[i][1]
tesbackup[idxnow][2] = tes[i][2]
}
obj.array2canvas(tesbackup)
})
</script>
And then for the script that used on that html file, is a js file named imagine.js.
imagine.js
function info(text){
console.info(text)
}
function pc(canvas){
this.canvas = canvas
this.context = this.canvas.getContext('2d')
this.width = 0
this.height = 0
this.imgsrc = ""
this.image2read = function(){
this.originalLakeImageData = this.context.getImageData(0,0, this.width, this.height)
this.resultArr = new Array()
this.tempArr = new Array()
this.tempCount = 0
for(var i=0; i<this.originalLakeImageData.data.length; i++){
this.tempCount++
this.tempArr.push(this.originalLakeImageData.data[i])
if(this.tempCount == 4){
this.resultArr.push(this.tempArr)
this.tempArr = []
this.tempCount = 0
}
}
info('image2read Success ('+this.imgsrc+') : '+this.width+'x'+this.height)
return this.resultArr
}
this.image2canvas = function(imgsrc){
var imageObj = new Image()
var parent = this
imageObj.onload = function() {
parent.canvas.width = imageObj.width
parent.canvas.height = imageObj.height
parent.context.drawImage(imageObj, 0, 0)
parent.width = imageObj.width
parent.height = imageObj.height
info('image2canvas Success ('+imgsrc+')')
}
imageObj.src = imgsrc
this.imgsrc = imgsrc
}
this.array2canvas = function(arr){
this.imageData = this.context.getImageData(0,0, this.width, this.height)
if(this.imageData.data.length != arr.length*4){
error("array2canvas Failed to Execute")
return false
}
for(var i = 0; i < arr.length; i++){
this.imageData.data[(i*4)] = arr[i][0]
this.imageData.data[(i*4)+1] = arr[i][1]
this.imageData.data[(i*4)+2] = arr[i][2]
this.imageData.data[(i*4)+3] = arr[i][3]
}
this.context.clearRect(0, 0, this.width, this.height)
this.context.putImageData(this.imageData, 0, 0)
info('Array2Canvas Success ('+this.imgsrc+')')
}
this.i2x = function(i){
return (i % this.width)
}
this.i2y = function(i){
return ((i - (i % this.width))/ this.width)
}
this.xy2i = function(x,y){
return (y * this.width) + (x)
}
}
I screenshot the output of the script, the image can be zoomed to a smaller image but can't be zoomed to a bigger image canvas
Original size of the image
Image size after I change the value to smaller value
But when I try to scroll it to a bigger value, the canvas get bigger but the images is disappeared. And I get the error "Cannot set property '0' of undefined".
Image size when I change the value to bigger value
Can someone point out what should I add or remove to get the image resize to bigger using this code??
Thanks in advance

Why is my first canvas clearing?

I've written the code below which works when creating one canvas object dynamically and filling it with pixels, however when I try to create multiples, it clears the first canvas for some reason. Anybody have any ideas as to why and how to fix it?
(JS FIddle doesn't seem to work so somewhat long paste here)
<head>
<script type="text/javascript">
function createnew_canvas()
{
var canvas_number = document.getElementById("hidden_counter").innerHTML.toString();
var new_canvas = parseInt(canvas_number) + 1;
document.getElementById("hidden_counter").innerHTML = new_canvas;
var mydoc = document.getElementById("canvas_area");
var mynewname = "canvas"+ canvas_number.toString();
mydoc.innerHTML = mydoc.innerHTML + '<canvas id="'+ mynewname +'" width="1000" height="600">canvas</canvas><br/>';
draw_canvas(canvas_number);
}
function setPixel(imageData, x, y, r, g, b, a)
{
index = (x + y * imageData.width) * 4;
imageData.data[index+0] = r;
imageData.data[index+1] = g;
imageData.data[index+2] = b;
imageData.data[index+3] = a;
}
function draw_canvas(canvasnum)
{
var myname = "canvas" + canvasnum;
element = document.getElementById(myname);
c = element.getContext("2d");
// read the width and height of the canvas
element.width = document.documentElement.clientWidth ;
element.height = document.documentElement.clientHeight ;
width = element.width;
height = element.height;
// create a new pixel array
imageData = c.createImageData(width, height);
for (i= 0; i < width;i++)
{
for (v =1; v <height - 400; v++)
{
if (i % 12 === 0 )
{
setPixel(imageData, i, 200 + v , 50* canvasnum, 50*canvasnum, 0, 255); // 255 opaque
}
else
{
setPixel(imageData, i, 200 + v, 0, 0, 50*canvasnum, 255); // 255 opaque
}
}
}
c.putImageData(imageData, 0, 0); // at coords 0,0
}
</script>
</head>
<body>
<div class="navbar">
<div class="title">Canvas Maker</div>
<div></div>
<div></div>
<div></div>
<div class="addnewcanvas" onclick="createnew_canvas();"> +</div>
<div id="hidden_counter">1</div>
</div>
<div id="canvas_area"></div>
</body>
It looks like you have:
mydoc.innerHTML = mydoc.innerHTML + '<canvas id="'+ mynewname +'" width="1000" height="600">canvas</canvas><br/>';
that will set the html of the element, but doing so will cause any state of the canvas that was there to be lost.
You might want to just try to append your new elements to the mydoc instead of setting the html.
Append The canvas like this
function createCanvas(id) {
var canvasMade = document.createElement("canvas");
canvasMade.id = id;
document.body.appendChild(canvasMade);
}
Hope this helped...

Images not loading on website

The problem I have is that when the page is loaded sometimes it displays all the images, sometimes just 2 images and sometimes all. I don´t know why this is happening.
Any ideas?
$('#banners .box img').each(function(index){
var randval = (index+1)*100;
var _this = $(this)
setTimeout(function(){
_this.attr('id' , 'banner' + index);
to_canvas('banner' + index, 300, 223);
}, randval)
});
to_canvas function:
function to_canvas(im,w,h){
var canvas;
var imageBottom;
var im_w = w;
var im_h = h;
var imgData;
var pix;
var pixcount = 0;
var paintrow = 0;
var multiplyColor = [70, 116, 145];
var x_offset = Math.floor(($('#'+im).attr('width') - im_w)/2);
var y_offset = Math.floor(($('#'+im).attr('height') - im_h)/2);
imageBottom = document.getElementById(im);
canvas = document.createElement('canvas');
canvas.width = im_w;
canvas.height = im_h;
imageBottom.parentNode.insertBefore(canvas, imageBottom);
ctx = canvas.getContext('2d');
ctx.drawImage(imageBottom, -x_offset , -y_offset);
imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
pix = imgData.data;
for (var i = 0 ; i < pix.length; i += 4) {
if(pixcount > im_w - (im_h - paintrow) ){
pix[i ] = multiply(multiplyColor[0], pix[i ]);
pix[i+1] = multiply(multiplyColor[1], pix[i+1]);
pix[i+2] = multiply(multiplyColor[2], pix[i+2]);
}
if(pixcount < im_w-1){
pixcount++;
}else{
paintrow++;
pixcount = 0;
}
}
ctx.putImageData(imgData, 0, 0);
$('#'+im).remove();
}
function multiply(topValue, bottomValue){
return topValue * bottomValue / 255;
}
I'm using the canvas function to add a triangle with multiply effect (like Photoshop).
Make sure the images are loaded :
$('#banners .box img').each(function(index, elem){
var randval = (index+1)*100,
self = this,
img = new Image(); // create image object
img.onload = function() { // wait until it's loaded
setTimeout(function(){
self.id = 'banner' + index;
to_canvas('banner' + index, 300, 223);
}, randval)
}
img.src = elem.src; // set source to same as elem
});
Wrap it all in this code to make sure the images are loaded before you execute your script. When you initially load your page, it caches the images(stores them in temp memory), but not before all your elements are rendered. When you reload, it reads the images from the cache–which is much faster than refetching the images again from the server–and therefore the images load about the same time everything else does. This results in visible images.
Like I said, to get your page to work, make sure everything is loaded, then run your script.
$(window).load(function(){
...your scripts(you can exclude functions definitions from this scope)
}

Categories