How to Copy an Image using Javascript

Coreysan 1,811 Reputation points
2022-10-28T17:57:41.223+00:00

I wrote a MVC page that uses a typical <input type=file"> object to upload a JPG file.
I use Javascript this way:

if (file.type.startsWith("image/")) {  
    const reader = new FileReader();  

    reader.readAsDataURL(file);  
    reader.onload = () => {  
        thumbnailElement.style.backgroundImage = `url('${reader.result}')`;  
    };  
} else {  
    thumbnailElement.style.backgroundImage = null;  
}  

So, with this instruction I use css to display the backgroundImage as a thumbnail, and I'm happy.

However, at the same time I'd like to actually display the uploaded image to 2 different objects,
but I have no idea how that works.

I tried this:

let previewElement = document.getElementById("previewbox_id");  
previewElement.src = thumbnailElement.src;  

I hope that by passing the contents of "src" from the thumbnail to the previewElement, I could see
two (2) images of the same JPG, just with different sizes.

No go!

If I use the FileReader a 2nd time, that does what I want, but that's a lot of extra work.

Is there a better way?

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-10-31T05:56:10.47+00:00

    Hi @Coreysan ,

    You can refer to the following code:

    255445-image.png

    Then use the following Scripts to preview the image: In the reader onload function display the images, view the source code:

    255496-image.png

    The result like this:

    255535-capture1.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.