gpt4 book ai didi

javascript - 检查图像透明度

转载 作者:技术小花猫 更新时间:2023-10-29 12:51:36 25 4
gpt4 key购买 nike

我有一个网站,人们可以在其中上传 PNG 图像并保存它。但在他们保存之前,我需要检查图像是否包含透明度。如果图像不是 24 位,有没有办法检查(我更喜欢 JavaScript)?

<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;
}
}

最佳答案

您可以为此目的使用此 Canvas 技术并根据您的需求自定义此代码
确保将 Canvas 调整为与图像相同的大小,否则在图像未覆盖 Canvas 的情况下,某些像素将是透明的。

c.width=element.width;
c.height=element.height;

示例代码和演示:

var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");

$p1=$('#results1');
$p2=$('#results2');

var img1=new Image();
img1.crossOrigin='anonymous'
img1.onload=start1;
img1.src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
function start1(){

canvas1.width=img1.width;
canvas1.height=img1.height;

ctx1.drawImage(img1,0,0);

var imgData=ctx1.getImageData(0,0,canvas1.width,canvas1.height);
var data=imgData.data;
var found1='Left canvas does not have transparency';
for(var i=0;i<data.length;i+=4){
if(data[i+3]<255){found1='Left canvas does have transparency';
break;
}
}

$p1.text(found1);

}


var img2=new Image();
img2.crossOrigin='anonymous'
img2.onload=start2;
img2.src="https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
function start2(){

canvas2.width=img2.width;
canvas2.height=img2.height;

ctx2.drawImage(img2,0,0);

var imgData=ctx2.getImageData(0,0,canvas2.width,canvas2.height);
var data=imgData.data;
var found2='Right canvas does not have transparency';
for(var i=0;i<data.length;i+=4){
if(data[i+3]<255){found2='Right canvas does have transparency';
break;
}
}

$p2.text(found2);

}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id=results1>Results:</p>
<p id=results2>Results:</p>
<canvas id="canvas1" width=300 height=300></canvas>
<canvas id="canvas2" width=300 height=300></canvas>

关于javascript - 检查图像透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41287823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com