Created
December 26, 2012 09:20
-
-
Save yomusu/4379080 to your computer and use it in GitHub Desktop.
This code is handling pixels on a array with only BufferedImage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.yom; | |
import java.awt.image.BufferedImage; | |
import java.io.File; | |
import java.io.IOException; | |
import javax.imageio.ImageIO; | |
public class ImageSample { | |
static public void main( String[] args ) throws IOException { | |
// PNG画像を読み込み | |
BufferedImage img1 = ImageIO.read( new File("ebi02.png") ); | |
int w = img1.getWidth(); | |
int h = img1.getHeight(); | |
// ピクセルを配列として取得 | |
int[] px = img1.getRGB( 0,0, w, h, null, 0, w ); | |
// グレースケール化 | |
for( int i=0; i<px.length; i++ ) | |
px[i] = convGray( px[i] ); | |
// 新しいBufferedImageを作成し、ピクセルを配列でセット | |
BufferedImage result = new BufferedImage( w, h, BufferedImage.TYPE_INT_RGB ); | |
result.setRGB( 0,0, w, h, px, 0, w ); | |
// BufferedImageをPNGとして保存 | |
ImageIO.write( result, "png", new File("gray.png") ); | |
} | |
static private int convGray( int argb ) { | |
int a = (argb>>24) & 0xff; | |
int r = (argb>>16) & 0xff; | |
int g = (argb>>8 ) & 0xff; | |
int b = (argb ) & 0xff; | |
int avr = ( r + g + b ) / 3; | |
int gray = avr & 0xff; | |
return (a<<24) | (gray<<16) | (gray<<8) | gray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment