I have a website where people can upload an PNG image and save it. But before they can save it, i need a check if the image contains transparency. Is there an way to check (i prefer JavaScript) if an image is not 24 bits?
<img id="imageId" src=#" onload="checkRestriction(this,'1')" alt=""/>
var isPng24Bit = false;
function checkRestriction(image, id) {
if(image.colorDepth != 24) {
PNGis24Bit = false;
} else {
PNGis24Bit = true;
}
}
you can use this canvas technique for this purpose and customize this code as your demand
Make sure you resize your canvas to the same size as the image or else some pixels will be transparent where the image doesn't cover the canvas.
Example code and Demo:
I post this as an alternative approach to check via the PNG file's header directly. This saves memory and doesn't have to iterate through pixels, and the same good performance will be the same regardless of image size.
You can do this by loading the file via
HTTPRequest
orFileReader
asArrayBuffer
, then simply check the file header structure using aDataView
.A PNG file always starts with the IHDR chunk so we only need to check if it's actually a PNG file and then assume the offset for the information telling the depth and type.
The depth field can be of value 1, 2, 4, 8 and 16 (1, 2, 4 being indexed, 8 = 24-bit or 8-bits per channel etc.).
The type field can be 0 (grayscale), 2 (true-color or RGB), 3 (indexed), 4 (grayscale + alpha) and 6 (RGB + alpha).
For details on the PNG file format and the IHDR header, see this link.
Same example but inserting image that is being checked into DOM: