Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.apache.commons.lang3.StringUtils;
- import javax.imageio.ImageIO;
- import java.awt.image.BufferedImage;
- import java.awt.image.DataBufferByte;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * Created by david on 12/17/14
- */
- public class Main
- {
- public static void main(String[] args) throws IOException
- {
- BufferedImage bufferedImage = ImageIO.read(Main.class.getResource("/annalisa-licciardi.png"));
- int[][][] result = getPixels(bufferedImage);
- for(int i = 0; i < result.length; i++)
- {
- for(int j = 0; j < result[i].length; j++)
- {
- System.out.println(i + " " + j + " " + intArrayToString(result[i][j]));
- }
- }
- }
- private static String intArrayToString(int[] integers)
- {
- List<String> output = new ArrayList<>();
- for(int i = 0; i < integers.length; i ++)
- output.add(Integer.toString(integers[i]));
- return StringUtils.join(output, ",");
- }
- private static int[][][] getPixels(BufferedImage image) {
- final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
- final int width = image.getWidth();
- final int height = image.getHeight();
- final boolean hasAlphaChannel = image.getAlphaRaster() != null;
- int[][][] result = new int[height][width][4];
- if (hasAlphaChannel) {
- final int pixelLength = 4;
- for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
- int[] pixelData = new int[4];
- pixelData[0] = (int) pixels[pixel] & 0xff;
- pixelData[1] = (int) pixels[pixel + 1] & 0xff;
- pixelData[2] = (int) pixels[pixel + 2] & 0xff;
- pixelData[3] = (int) pixels[pixel + 3] & 0xff;
- result[row][col] = pixelData;
- /*
- int argb = 0;
- argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
- argb += ((int) pixels[pixel + 1] & 0xff); // blue
- argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
- argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
- result[row][col] = argb;
- col++;
- if (col == width) {
- col = 0;
- row++;
- }
- */
- }
- } else {
- final int pixelLength = 3;
- for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
- int[] pixelData = new int[4];
- pixelData[0] = 0;
- pixelData[1] = (int) pixels[pixel] & 0xff;
- pixelData[2] = (int) pixels[pixel + 1] & 0xff;
- pixelData[3] = (int) pixels[pixel + 2] & 0xff;
- result[row][col] = pixelData;
- /*
- int argb = 0;
- argb += -16777216; // 255 alpha
- argb += ((int) pixels[pixel] & 0xff); // blue
- argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
- argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
- result[row][col] = argb;
- col++;
- if (col == width) {
- col = 0;
- row++;
- }
- */
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement