1

I have a product image with white background color. Image source link comes from client side database. So, I need to convert image in to a transparent background color (from white) with JS or CSS.

Anyone know a better solution for this?

I heard about by adding bkgnd=transparent value to image URL, Is it a possible way?

Searched a lot time in google, but didn't get any proper solution.

See my code:

.container {
  width: 100%;
  max-width: 600px;
  padding: 10px;
  background: url(https://picsum.photos/200/300) center center no-repeat;
  background-size: cover;
}

img {
  width: 100%;
}
<div class="container">
  <img src="https://imgd.aeplcdn.com/1056x594/n/suk7osa_1474663.jpg?q=85">
</div>

JSFiddle

vishnu
  • 2,848
  • 3
  • 30
  • 55
  • This is basically impossible. What you can do is draw the loaded image onto a ``, then get its `imageData`, iterate over the individual pixel data and set all pixels with 255,255,255 to fully transparent. However this will also turn fully white pixels inside the car to transparent. If you want to avoid that, you need to preprocess the image server-side, using a suitable image processing library. –  Apr 22 '20 at 12:05
  • Better to save the image with a transparent background. And it the image is needed with a colored background, you can wrap the image into an element with that color as background color. – Teemu Apr 22 '20 at 12:07
  • @ChrisG okay.. do you have any sample link? – vishnu Apr 22 '20 at 12:18
  • 1
    Sure: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData –  Apr 22 '20 at 12:20
  • you can check: https://stackoverflow.com/questions/9182978/semi-transparent-color-layer-over-background-image – Uday Chauhan Apr 22 '20 at 12:31

1 Answers1

-1

You should to use png without white background. You can not change opacity only white background and leave the car untouched

Andrey RF
  • 342
  • 3
  • 13
  • Transparency is not done in HTML but is a part of the image itself. The browser will see the image as a PNG and display it as a PNG automatically. To add transparency to the image, you will have to edit the file with a graphics editor like Photoshop. – Uday Chauhan Apr 22 '20 at 12:33
  • 1
    This is what I meant when I wrote that you need a png without a white background – Andrey RF Apr 22 '20 at 13:40
  • PNG without background won't help. It will display white and grey pixels. – Uday Chauhan Apr 22 '20 at 14:27
  • how can the absence of color be grey and white pixels? – Andrey RF Apr 22 '20 at 18:37
  • I just tried it. I took this pic, delete white backgroud in `paint.net` and save resalt as `image.png` and now if I use this image like background, I have not any white background, only car – Andrey RF Apr 22 '20 at 18:42