简体   繁体   中英

How to detect if image has transparent background and white text

Has anyone found an efficient way to detect if an image has a transparent background with white text inside the image? Ie When this image is displayed on a white background, this will then not be displayed.

The correct thing to do here would be to use a different image, which may be the end solution, although in the first instance I'm wanting to see if this can be automated. The ideal solution in my mind is to give the image a CSS background of say 'lightblue' if the image has a transparent background with white text contained, so then the image will show.

The challenges here is, what is classified as white text? A single pixel of white or over 30% of the non-transparent part of the image as white or something else?

Has anyone found something where this is possible? Preferably using either Java to process the image and determine if a background needs to be applied so some kind of flag can be set, or even better, a nice CSS or JavaScript trick that I haven't come across.

  1. HTML/CSS : A common trick in that doesn't require any coding at all to make overlay text visible, regardless of the color/brightness of the image is to add a text-shadow:

     text-shadow: 0px 0px 3px rgba(0, 0, 0, 1); 

    Just use 0px for horizontal/vertical shadow offset and a mild blur, so you actually get a pretty opaque border around the text.


  1. JS: If you really want to inspect pixel by pixel and get a sense of the brightness/colours that are present in the part of the image you're text will be overlayed on.

    Using HTML5's canvas, you can draw your image in the canvas and inspect pixel by pixel and calculate the average RGB values and adapt the text-color to this. Even if you get this right, this is still an average and the text may still bleed into the image when the color of the text is too close.

    I guess with some googling, you'll find canvas wrapper libraries who do this for you in JS.


  1. Java : Same approach as with JS - determine what rectangle of your image will be covered by text and get the average color.

    Using BufferedImage , you can get every pixel in memory for you to inspect, regardless of the image type (jpeg, png, ...).


I'd go for the quick-win text-shadow solution, this requires no coding at all. I'd only go for 2 or 3, if you really need the image saved as image and not just shown to the user on a webpage .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM