マイペースなプログラミング日記

DTMやプログラミングにお熱なd-kamiがマイペースに書くブログ

モノクロ画像の作成

なんとなくモノクロ画像を作成したくなり、プログラム作成。Googleで「モノクロ画像の作成」で検索して見つけてきた式を使ってカラー画像をモノクロ画像に変換した。大学の授業で習ったような習わなかったような…

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

public class MonoImage{
    public static void main(String[] args) throws Exception{
        BufferedImage image = ImageIO.read(new File("nekobean.png"));
        int height = image.getHeight();
        int width = image.getWidth();

        for(int y = 0; y  < height; y++){
            for(int x = 0;  x < width; x++){
                int rgb = image.getRGB(x, y);

                int alpha = (rgb >> 24) & 0xFF;
                int red   = (rgb >> 16) & 0xFF;
                int green = (rgb >> 8) & 0xFF;
                int blue  = rgb & 0xFF;

                int mono = (int)(0.299 * red + 0.587 * green + 0.114 * blue);

                mono = (alpha << 24) + (mono << 16) + (mono << 8) + mono;

                image.setRGB(x, y, mono);
            }
        }

        ImageIO.write(image, "png", new File("mono_nekobean.png"));
    }
}

実行結果


ねこび〜ん by カネウチカズコ is licensed under a Creative Commons 表示-継承 2.1 日本 License.