使用JavaScript调整画布图像的亮度和对比度

12

我有一个放在标签中的图片

var img = new Image();
ctx.drawImage(img,0,0,img.width,img.height);
ecc...

如何使用JavaScript更改此图像的亮度和对比度?

Tnx


1
-1:您至少可以告诉我您的问题是关于哪种编程语言的。 - Tomas Narros
添加了JavaScript标签。这样,就有更多的机会让JavaScript专家查看问题。 - Tomas Narros
4个回答

5

我知道至少有一个JavaScript库可以实现这个功能,它就是Pixastic

使用方法可能如下所示。

Pixastic.process(canvas, 'brightness',
    {
        'brightness': 60,
        'contrast': 0.5,
        'leaveDOM': true
    },
    function(img) {
        ctx.drawImage(img, 0, 0);
    }
);

该库旨在与页面中的图像一起使用,并用包含渲染结果的canvas元素替换它们。

但是在上面的代码中,我传递了一个canvas元素而不是一个图像,并包含了'leaveDOM'属性,以防止pixastic库将您的canvas在DOM中替换为它创建的canvas。

为了显示结果,我包括了回调函数,它只是做ctx.drawImage把内容放入您原始的canvas内。

希望这讲得通。

您可以查看文档以获取更多示例。Pixastic文档


1
Pixastic的链接指向不同的页面。 - Franchy
感谢您的回答,我已更新了 Pixastic 文档的链接。 - Nicolae Olariu
尽管Pixastic文档中提到了“使用Legacy”,但他们的非遗留模式似乎并没有实际实现Photoshop的现代(基于曲线的内部)调整图层。 - Keavon

0

坏了,链接失效了 :\ - Wallace Vizerra
更新了损坏的链接。 - Brandon Johnson

-2

你可以试试这个,看看注释

<script type="application/javascript">  

function clickMeEvent(obj)
{
if (obj.style.opacity=="0.9")
    {
    obj.style.opacity="0.7";
    }
else if (obj.style.opacity=="0.7")
    {
    obj.style.opacity="0.5";        
    }
else if (obj.style.opacity=="0.5")
    {
    obj.style.opacity="0.3";        
    }
else if (obj.style.opacity=="0.3")
    {
    obj.style.opacity="0.1";        
    }
else
    {
    obj.style.opacity="0.0";

    }
}

</script>


请将以下代码放在<html>标签的顶部:<div> <img style="opacity:0.9;" src="你的图片位置" onclick="clickMeEvent(this)"> </div> - Laxman
2
你不是认真的吧。 - zrooda

-3
你可以尝试这个(C#代码):
 Bitmap originalImage;
 Bitmap adjustedImage;
 double brightness = 1.0f; // no change in brightness
 double constrast = 2.0f; // twice the contrast
 double gamma = 1.0f; // no change in gamma

 float adjustedBrightness = brightness - 1.0f;
 float[][] ptsArray ={
                new float[] {contrast, 0, 0, 0, 0}, // scale red
                new float[] {0, contrast, 0, 0, 0}, // scale green
                new float[] {0, 0, contrast, 0, 0}, // scale blue
                new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha
                new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}};

 imageAttributes = new ImageAttributes();
 imageAttributes.ClearColorMatrix();
 imageAttributes.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
 imageAttributes.SetGamma(gamma, ColorAdjustType.Bitmap);
 Graphics g = Graphics.FromImage(adjustedImage);
 g.DrawImage(originalImage, new Rectangle(0,0,adjustedImage.Width,adjustedImage.Height)
            ,0,0,bitImage.Width,bitImage.Height,
 GraphicsUnit.Pixel, imageAttributes);

@PizzaiolaGorgonzola 这个问题最初没有提到语言。 - xehpuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接