Access the <img> content and convert to base64 - javascript

I am loading an image in React from a URL external to my app:
<img id={selectedImage.id} src={selectedImage.url} \>
Now I want the user to be able to press a button and the app should store the image content as base64 data in some variable.
Is there any way for me to reference this specific <img> in React and convert the image content into its base64 text representation?
I have seen various solutions on Stack Overflow. Some of these solutions attempt to retrieve the image from a URL again (which caused CORS issues in my case and also represents redundant loading). E.g. I have looked here:
Convert image from url to Base64
If I wanted to implement this solution I would not know how to do so in a React environment:
I don't know how this document.getElementById("imageid") works in a React environment; and
I would also not know where to place the function in React that is supposed to draw a canvas.

you can use ref and when image load call getBas64Image method and pass img tag to it
import { useEffect, useRef } from "react";
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/?[A-z]*;base64,/);
}
//var base64 = getBase64Image(document.getElementById("imageid"));
//method 1: use ref
export function Img({imageSource}){
const imageRef = useRef();
imageRef.current.onload = ()=>getBase64Image(imageRef.current);
// imageRef.current is same of document.getElementById
return <img ref={imageRef} src={imageSource} />
}

Related

Get image dimension from blob in React Native

Let's suppose I'm calling an API which serves images with random dimensions.
I need to know the width and the height for each image before rendering, because I need to do some computations for the precise layout I want.
With Web Apis, I've made this and it's working fine:
const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();
const img = new Image();
img.src = URL.createObjectURL(blob);
console.log(img.src);
img.onload = () => {
console.log(img.width, img.height);
};
The problem is that with React Active, we don't have access to the Web Api Image Object.
Image is a component on React Native.
Here's where I'm at:
const res = await fetch("https://picsum.photos/200/300");
const blob = await res.blob();
So basically the binary data is stored in RAM right now, but I can't find any way to interpret this data into an image and get the dimensions.
React Native Image component has built-in getSize method. If you can transform your blob to URI than you can use the code below.
Image.getSize(myUri, (width, height) => { console.log(width, height)});

How to select file, fix orientation, and add to canvas

My site allows users to upload their own photos. I've learned that this is trickier than first expected and although I can get each of the components working individually I'm not successfully getting them to produce the outcome I need when combining them. I believe the issue is my lack of understanding around the outputs of the functions i'm using.
I think what I need to do is:
Let the user choose the file to upload
Check / fix the orientation
Display the image in a canvas
Convert the canvas to base64 (to upload to Firebase)
Upload the item
Let the user choose the file to upload
$(document).on('change','#fileUpload',function(e) {
correctImageOrientation(e);
});
Check / fix the image orientation
I'm using image-load (link) for my orientation changes.
function correctImageOrientation(e) {
loadImage(
e.target.files[0],
function (img) {
// document.body.appendChild(img); // Note: this successfully appends the image in the correct orientation to the body - but I need to do this to a canvas to I call:
addImageToCanvas(img);
},
{
orientation: true
}
);
Display the image in a canvas
This part fails. If I pass in the selected file using e.target.files[0] and create an objectURL then it works. This is why I think the img i'm passing in needs to be read / displayed on the canvas differently.
function addImageToCanvas(img) {
img.onload = function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, 300, 300);
console.log("Ending img.onload"); // This is never reached
}
}
I can then successfully convert the file to base64 and upload to Firebase.
I think there must be an easier way to achieve what I want which is for people to upload an image, for the orientation to be correct, and for this to be stored online.
EDIT: To store the image in firebase I am using this to convert the image back to a blob.
I have replaced addImageToCanvas with the function below which was taken then modified from David Walsh's site. Because I'm passing in an image I needed to convert this to a canvas.
function convertImageToCanvas(image) {
var canvas = document.getElementById("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
}

Javascript convert image to PNG

After seing alot of examples here, and try to use them they work in some degree, but it doesn't true convert the image.
The image as the extension now png and open as such, but if I go into properties it stills says :
on C# and HTML the image shows without any problem, but I'm using the language c++ and it won't show on the QPushButton
This is an example of the code that I'm using on the javascript to convert the image:
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
return canvas;
}
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
return image;
}
So the image is saved throught base64 to png opens as such on many programs but on the one that I'm trying to do it wont.
How to I properly convert an image to png ?! Since this method isn't working

set background-image from localStorage base64 string

I have a function that encodes an image into base64 string and stores it into localStorage. I am trying to retrieve the image from localStorage and use it to set a background-image with jQuery.
Everything is working right, but the image isn't displaying. When I inspect the element in the browser, the single quotes around the 'data' uri aren't being inserted. I don't know if this is the problem or not.
Here is my code
function to encode and store image:
var img = document.getElementById("elephant");
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
var dataURL = canvas.toDataURL("image/png");
console.log(dataURL);
return dataURL;
}
jQuery to set the image:
localStorage.setItem("background" , getBase64Image(img));
console.log(localStorage);
background = localStorage.getItem("background")
console.log(background);
$("#elephant2").css('background-image' , 'url(' +background+ ')');
I thought the issue was missing quotes, but it was actually corrupted/incomplete base64 data string. I placed the function inside window.onload = function () so the image loaded entirely before converting to a string and it works like a charm/

Javascript: loading image from bytearray

In Javascript you have the ByteArray type and some views on it as described here:
https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays
is it possible to store image data in such bytes and if yes, how can i display such an image? png or jpg?
Yes, you can store an image using the typed arrays.
Im not sure what you want actually.
If you want to create an HTMLImageElement from a ByteArray, you can do something similar as cited in here and here.
If you want to get the bytes from an Image, that would be trickier. You can draw the ImageElement to HTML canvas, and them get the URI back using toDataURL.
I just tried to get the data using canvas and it worked.
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
myCanvas.width = img.width;
myCanvas.height = img.height;
ctx.drawImage(img,0,0); // Or at whatever offset you like
alert(myCanvas.toDataURL());
};
img.src = "logo4w.png";
Although, the method toDataURL() do not allow you to perform this operation if the image you draw on canvas comes from outside the website domain.

Categories

Resources