views:

67

answers:

3

I have an image in a tag

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

How is possible to change the Brightness and Contrast of this image with javascript?

Tnx

A: 

You can try this (c# code):

 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);
Jeff Norman
+1  A: 
# CONTRAST: adjust contrast by multiplier
img.reset.fit(w,h)
img.contrast(2.0)
canvas.draw(img,x,y) 
canvas.text("contrast",x,y-15)
x += xoffset

# BRIGHTNESS: adjust brightness
img.reset.fit(w,h)
img.brightness(0.5)
canvas.draw(img,x,y)
canvas.text("brightness",x,y-15)
x += xoffset

Maybe this link will help.. have a look. I have seen examples of this online for photogalaries to adjust your image.. Maybe a quick google search can help.

http://hcg.drtoast.com/image-color-adjustments/

traumatized
+2  A: 

There's at least one javascript library I know of which can do this, Pixastic

Usage might look like this.

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

The library is kind of intended to work with images within your page and it replaces them with canvas elements which contain the rendered result.

But in the code above I've passed in a canvas element rather than an image and included the 'leaveDOM' property to prevent the pixastic library from swapping your canvas in the DOM for the one it creates.

To display the results I've included the callback function which just does ctx.drawImage to put the contents into your original canvas.

Hope that makes sense.

You can check the documentation for more examples. Pixastic Documentation

Kyle Jones