Sepia tone image filter for Java

M

Macky G

After spending hours searching the web and not finding an answer, I
finally put together a function to create sepia images with Java.
This function produces amazing results, I'm very happy with it. I
hope it saves everyone time...

(You'll need your image to be in a BufferedImage object. The web has
plenty of tutorials for that.)


/**
*
* @param img Image to modify
* @param sepiaIntensity From 0-255, 30 produces nice results
* @throws Exception
*/
public static void applySepiaFilter(BufferedImage img, int
sepiaIntensity) throws Exception
{
// Play around with this. 20 works well and was recommended
// by another developer. 0 produces black/white image
int sepiaDepth = 20;

int w = img.getWidth();
int h = img.getHeight();

WritableRaster raster = img.getRaster();

// We need 3 integers (for R,G,B color values) per pixel.
int[] pixels = new int[w*h*3];
raster.getPixels(0, 0, w, h, pixels);

// Process 3 ints at a time for each pixel. Each pixel has 3 RGB
colors in array
for (int i=0;i<pixels.length; i+=3)
{
int r = pixels;
int g = pixels[i+1];
int b = pixels[i+2];

int gry = (r + g + b) / 3;
r = g = b = gry;
r = r + (sepiaDepth * 2);
g = g + sepiaDepth;

if (r>255) r=255;
if (g>255) g=255;
if (b>255) b=255;

// Darken blue color to increase sepia effect
b-= sepiaIntensity;

// normalize if out of bounds
if (b<0) b=0;
if (b>255) b=255;

pixels = r;
pixels[i+1]= g;
pixels[i+2] = b;
}
raster.setPixels(0, 0, w, h, pixels);
}
 
Q

Qu0ll

Macky G said:
After spending hours searching the web and not finding an answer, I
finally put together a function to create sepia images with Java.
This function produces amazing results, I'm very happy with it. I
hope it saves everyone time...

(You'll need your image to be in a BufferedImage object. The web has
plenty of tutorials for that.)

[code snipped]

Thanks for that - it's a nice effect. It crashed the first time I used it
because the image I tried it on had alpha values (i.e. a translucent image)
and your code does not cater for that. I simply changed the code to use a
larger array (based on width * height * 4) and also to loop through using
increments of 4. You might like to change the code to check for translucent
images and handle them appropriately.

--
And loving it,

-Qu0ll (Rare, not extinct)
_________________________________________________
(e-mail address removed)
[Replace the "SixFour" with numbers to email me]
 
M

Macky G

Qu0ll: Thanks for the comment, that's great advice. I'll definitely
use your code to handle alpha images.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top