如何在Javascript中获取图像颜色模式(CMYK,RGB ...) [英] How to get image color mode (CMYK, RGB ...) in Javascript

查看:313
本文介绍了如何在Javascript中获取图像颜色模式(CMYK,RGB ...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript可以检查图像的颜色模式吗?

can the JavaScript check the color mode of a image?

我做了很多搜索,但我唯一看到的是颜色模式转换(但是转换希望你设置原始颜色模式)

I did a lot of search about this but the only thing I saw was color mode convert (but the convert wants you to set the original color mode)

我添加: - 允许 - 文件从文件访问在画布中完全控制img,因为我使用的是GoogleChrome

I add this: --allow-file-access-from-files to have a full control of img in canvas beacause I am using GoogleChrome

Html

<canvas id="canvas" width=6000 height=7919></canvas>

Js

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.crossOrigin = "anonymous";
img.onload = start;
img.src = "file:///D:/vincent-van-gogh-the-starry-night-picture-157544-2.png";


推荐答案

是的 - 基本上JavaScript能够确定颜色模式一个png,但因此它需要
1.将png转换为base64
2.将base64转换为字节数组
3.读取/解析关于png规范的数组

Yes - basically JavaScript is able to determine the color mode of a png, but therefore it would be required to 1. convert png to base64 2. convert base64 to byte array 3. reading / parsing the array regarding png specification

可能的方法如下:

var PNG = {

        parse: function(imgTag) {
            var base64 = PNG.asBase64(imgTag);
            var byteData = PNG.utils.base64StringToByteArray(base64);
            var parsedPngData = PNG.utils.parseBytes(byteData);

            return PNG.utils.enrichParsedData(parsedPngData);
        },

        asBase64: function(imgTag) {
            var canvas = document.createElement("canvas");
            canvas.width = imgTag.width; 
            canvas.height = imgTag.height; 
            var ctx = canvas.getContext("2d"); 
            ctx.drawImage(imgTag, 0, 0); 
            var dataURL = canvas.toDataURL("image/png");
            return dataURL.split('base64,')[1];
        },

        utils: {
            base64StringToByteArray: function(base64String) {
                //http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
                var byteCharacters = atob(base64String);
                var byteNumbers = new Array(byteCharacters.length);
                for (var i = 0; i < byteCharacters.length; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(i);
                }
                return new Uint8Array(byteNumbers);
            },

            parseBytes: function(bytes) {
                var pngData = {};
                //see https://en.wikipedia.org/wiki/Portable_Network_Graphics

                //verify file header
                pngData['headerIsValid'] = bytes[0] == 0x89
                            && bytes[1] == 0x50
                            && bytes[2] == 0x4E
                            && bytes[3] == 0x47
                            && bytes[4] == 0x0D
                            && bytes[5] == 0x0A
                            && bytes[6] == 0x1A
                            && bytes[7] == 0x0A

                if (!pngData.headerIsValid) {
                    console.warn('Provided data does not belong to a png');
                    return pngData;
                }

                //parsing chunks
                var chunks = [];

                var chunk = PNG.utils.parseChunk(bytes, 8);
                chunks.push(chunk);

                while (chunk.name !== 'IEND') {
                    chunk = PNG.utils.parseChunk(bytes, chunk.end);
                    chunks.push(chunk);
                }

                pngData['chunks'] = chunks;
                return pngData;
            },

            parseChunk: function(bytes, start) {
                var chunkLength = PNG.utils.bytes2Int(bytes.slice(start, start + 4));

                var chunkName = '';
                chunkName += String.fromCharCode(bytes[start + 4]);
                chunkName += String.fromCharCode(bytes[start + 5]);
                chunkName += String.fromCharCode(bytes[start + 6]);
                chunkName += String.fromCharCode(bytes[start + 7]);

                var chunkData = [];
                for (var idx = start + 8; idx<chunkLength + start + 8; idx++) {
                    chunkData.push(bytes[idx]);
                }

                //TODO validate crc as required!

                return {
                    start: start,
                    end: Number(start) + Number(chunkLength) + 12, //12 = 4 (length) + 4 (name) + 4 (crc)
                    length: chunkLength,
                    name: chunkName,
                    data: chunkData,
                    crc: [
                        bytes[chunkLength + start + 8],
                        bytes[chunkLength + start + 9],
                        bytes[chunkLength + start + 10],
                        bytes[chunkLength + start + 11]
                    ],
                    crcChecked: false
                };
            },

            enrichParsedData: function(pngData) {
                var idhrChunk = PNG.utils.getChunk(pngData, 'IDHR');

                //see http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
                pngData.width = PNG.utils.bytes2Int(idhrChunk.data.slice(0, 4));
                pngData.height = PNG.utils.bytes2Int(idhrChunk.data.slice(4, 8));
                pngData.bitDepth = PNG.utils.bytes2Int(idhrChunk.data.slice(8, 9));
                pngData.colorType = PNG.utils.bytes2Int(idhrChunk.data.slice(9, 10));
                pngData.compressionMethod = PNG.utils.bytes2Int(idhrChunk.data.slice(10, 11));
                pngData.filterMethod = PNG.utils.bytes2Int(idhrChunk.data.slice(11, 12));
                pngData.interlaceMethod = PNG.utils.bytes2Int(idhrChunk.data.slice(12, 13));

                pngData.isGreyScale = pngData.colorType == 0 || pngData.colorType == 4;
                pngData.isRgb = pngData.colorType == 2 || pngData.colorType == 6;
                pngData.hasAlpha = pngData.colorType == 4 || pngData.colorType == 6;
                pngData.hasPaletteMode = pngData.colorType == 3 && PNG.utils.getChunk(pngData, 'PLTE') != null;

                return pngData;
            },

            getChunks: function(pngData, chunkName) {
                var chunksForName = [];
                for (var idx = 0; idx<pngData.chunks.length; idx++) {
                    if (pngData.chunks[idx].name = chunkName) {
                        chunksForName.push(pngData.chunks[idx]);
                    }
                }
                return chunksForName;
            },

            getChunk: function(pngData, chunkName) {
                for (var idx = 0; idx<pngData.chunks.length; idx++) {
                    if (pngData.chunks[idx].name = chunkName) {
                        return pngData.chunks[idx];
                    }
                }
                return null;
            },

            bytes2Int: function(bytes) {
                var ret = 0;

                for (var idx = 0; idx<bytes.length; idx++) {
                    ret += bytes[idx];
                    if (idx < bytes.length - 1) {
                        ret = ret << 8;
                    }
                }

                return ret;
            }
        }
    }

可以使用如下:

var pngData = PNG.parse(document.getElementById('yourImageId'));
console.log(pngData);

它包含一些信息,如颜色模式,块数,块本身,位深度等。

It contains some information, like color mode, number of chunks, the chunks itself, bit depth, etc.

希望有所帮助。

这篇关于如何在Javascript中获取图像颜色模式(CMYK,RGB ...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆