Java BufferedImage to RGB imageToPixels(BufferedImage image)

Here you can find the source of imageToPixels(BufferedImage image)

Description

image To Pixels

License

Apache License

Declaration

public static int[][] imageToPixels(BufferedImage image) 

Method Source Code

//package com.java2s;
/*//from w  ww . j a va 2 s  . c o  m
 * Copyright 2009-2012 Michael Tamm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;

public class Main {
    public static int[][] imageToPixels(BufferedImage image) {
        if (image == null) {
            return null;
        }
        int w = image.getWidth();
        int h = image.getHeight();
        int[][] pixels = new int[w][h];
        Raster raster = image.getRaster();
        if (raster.getTransferType() == DataBuffer.TYPE_BYTE) {
            byte[] bytes = (byte[]) raster.getDataElements(0, 0, w, h, null);
            int bytesPerPixel = (bytes.length / (w * h));
            ColorModel colorModel = image.getColorModel();
            byte[] buf = new byte[bytesPerPixel];
            for (int x = 0; x < w; ++x) {
                for (int y = 0; y < h; ++y) {
                    System.arraycopy(bytes, (x + y * w) * bytesPerPixel, buf, 0, bytesPerPixel);
                    pixels[x][y] = colorModel.getRGB(buf) & 0xFFFFFF;
                }
            }
            return pixels;
        } else {
            throw new RuntimeException("transfer type " + raster.getTransferType() + " not implemented yet");
        }
    }
}

Related

  1. getRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels)
  2. getRGB(BufferedImage img)
  3. getRgbFromImage(BufferedImage image)
  4. getRGBPixels(BufferedImage img)
  5. imageToMatrix(BufferedImage image)
  6. imageToRGBABuffer(BufferedImage img)
  7. imageToRgbaBufferedImage(final Image image)