Java Code Examples for java.awt.image.BufferedImage.TYPE_BYTE_GRAY

The following are Jave code examples for showing how to use TYPE_BYTE_GRAY of the java.awt.image.BufferedImage class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: finding-the-planets   File: ImageTest.java   View Source Code Vote up 7 votes
@Test
public void createAnGrayPngImage() throws IOException {
    int m = 5;
    int n = 5;
    BufferedImage image = new BufferedImage(m, n, BufferedImage.TYPE_BYTE_GRAY);
    WritableRaster raster = image.getRaster();

    for (int x = 0; x < m; x++) {
        for (int y = 0; y < m; y++) {
            int index = 51 * x + 10*y;
            raster.setPixel(x, y, new int[]{ index });
        }
    }

    File output = new File("src/test/resources/png-test.gray.png");
    ImageIO.write(image, "png", output);
}
 
Example 2
Project: jdk8u-jdk   File: EffectUtils.java   View Source Code Vote up 6 votes
/**
 * <p>Writes a rectangular area of pixels in the destination <code>BufferedImage</code>. Calling this method on an
 * image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code>
 * will unmanage the image.</p>
 *
 * @param img    the destination image
 * @param x      the x location at which to start storing pixels
 * @param y      the y location at which to start storing pixels
 * @param w      the width of the rectangle of pixels to store
 * @param h      the height of the rectangle of pixels to store
 * @param pixels an array of pixels, stored as integers
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and of length &lt; w*h
 */
static void setPixels(BufferedImage img,
                             int x, int y, int w, int h, byte[] pixels) {
    if (pixels == null || w == 0 || h == 0) {
        return;
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length >= w*h");
    }
    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
        WritableRaster raster = img.getRaster();
        raster.setDataElements(x, y, w, h, pixels);
    } else {
        throw new IllegalArgumentException("Only type BYTE_GRAY is supported");
    }
}
 
Example 3
Project: qrcode-utils   File: BufferedImageLuminanceSource.java   View Source Code Vote up 6 votes
public BufferedImageLuminanceSource(BufferedImage image, int left, int top,
                                    int width, int height) {
  super(width, height);

  int sourceWidth = image.getWidth();
  int sourceHeight = image.getHeight();
  if (left + width > sourceWidth || top + height > sourceHeight) {
    throw new IllegalArgumentException(
      "Crop rectangle does not fit within image data.");
  }

  for (int y = top; y < top + height; y++) {
    for (int x = left; x < left + width; x++) {
      if ((image.getRGB(x, y) & 0xFF000000) == 0) {
        image.setRGB(x, y, 0xFFFFFFFF);// = white
      }
    }
  }

  this.image = new BufferedImage(sourceWidth, sourceHeight,
    BufferedImage.TYPE_BYTE_GRAY);
  this.image.getGraphics().drawImage(image, 0, 0, null);
  this.left = left;
  this.top = top;
}
 
Example 4
Project: openjdk-jdk10   File: EffectUtils.java   View Source Code Vote up 6 votes
/**
 * <p>Writes a rectangular area of pixels in the destination <code>BufferedImage</code>. Calling this method on an
 * image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code>
 * will unmanage the image.</p>
 *
 * @param img    the destination image
 * @param x      the x location at which to start storing pixels
 * @param y      the y location at which to start storing pixels
 * @param w      the width of the rectangle of pixels to store
 * @param h      the height of the rectangle of pixels to store
 * @param pixels an array of pixels, stored as integers
 * @throws IllegalArgumentException is <code>pixels</code> is non-null and of length &lt; w*h
 */
static void setPixels(BufferedImage img,
                             int x, int y, int w, int h, byte[] pixels) {
    if (pixels == null || w == 0 || h == 0) {
        return;
    } else if (pixels.length < w * h) {
        throw new IllegalArgumentException("pixels array must have a length >= w*h");
    }
    int imageType = img.getType();
    if (imageType == BufferedImage.TYPE_BYTE_GRAY) {
        WritableRaster raster = img.getRaster();
        raster.setDataElements(x, y, w, h, pixels);
    } else {
        throw new IllegalArgumentException("Only type BYTE_GRAY is supported");
    }
}
 
Example 5
Project: Pixie   File: Utils.java   View Source Code Vote up 6 votes
/**
 * Copy one buffered image to another.
 *
 * @param src - source image
 * @param dst - destination image
 */
public static void copySrcIntoDstAt(final BufferedImage src, final BufferedImage dst) {
    byte[] srcBuf = getByteData(src);
    byte[] dstBuf = getByteData(dst);
    int representationFactor;

    // width * hight * 3 because of rgb components and byte representation
    switch (src.getType()) {
        case BufferedImage.TYPE_BYTE_GRAY:
        case BufferedImage.TYPE_BYTE_INDEXED:
            representationFactor = 1;
            break;
        case BufferedImage.TYPE_3BYTE_BGR:
            representationFactor = 3;
            break;
        case BufferedImage.TYPE_4BYTE_ABGR:
            representationFactor = 4;
            break;
        default:
            representationFactor = 3;
            break;
    }

    System.arraycopy(srcBuf, 0, dstBuf, 0, src.getWidth() * src.getHeight() * representationFactor);
}
 
Example 6
Project: jdk8u-jdk   File: OpCompatibleImageTest.java   View Source Code Vote up 6 votes
private static String describeType(int type) {
    switch(type) {
    case BufferedImage.TYPE_3BYTE_BGR:
        return "TYPE_3BYTE_BGR";
    case BufferedImage.TYPE_4BYTE_ABGR:
        return "TYPE_4BYTE_ABGR";
    case BufferedImage.TYPE_BYTE_GRAY:
        return "TYPE_BYTE_GRAY";
    case BufferedImage.TYPE_INT_ARGB:
        return "TYPE_INT_ARGB";
    case BufferedImage.TYPE_INT_BGR:
        return  "TYPE_INT_BGR";
    case BufferedImage.TYPE_INT_RGB:
        return "TYPE_INT_RGB";
    case BufferedImage.TYPE_BYTE_INDEXED:
        return "TYPE_BYTE_INDEXED";
    default:
        throw new RuntimeException("Test FAILED: unknown type " + type);
    }
}
 
Example 7
Project: klavier   File: MatrixVis.java   View Source Code Vote up 6 votes
public static BufferedImage makeGrayscaleImage(float[][] mat) {
      mat = padAndNormalize(mat);
final BufferedImage img = new BufferedImage(Math.min(mat.length, maxDim), Math.min(mat[0].length, maxDim), BufferedImage.TYPE_BYTE_GRAY);
WritableRaster writeableRaster = img.getRaster();
for (int i=0; i<writeableRaster.getWidth(); ++i) {
	for (int j=0; j<writeableRaster.getHeight(); ++j) {
		writeableRaster.setPixel(i, writeableRaster.getHeight()-1-j, new float[] { mat[i][j] * 255 });
	}
}
      return img;
  }
 
Example 8
Project: Image-Stegano   File: ImageUtility.java   View Source Code Vote up 6 votes
public BufferedImage thresholdImage(BufferedImage image, int threshold) {
    BufferedImage result = new BufferedImage(image.getWidth(), 
            image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    result.getGraphics().drawImage(image, 0, 0, null);
    WritableRaster raster = result.getRaster();
    int[] pixels = new int[image.getWidth()];
    for (int y = 0; y < image.getHeight(); y++) {
        raster.getPixels(0, y, image.getWidth(), 1, pixels);
        for (int i = 0; i < pixels.length; i++) {
            if (pixels[i] < threshold) {
                pixels[i] = 0;
            } else {
                pixels[i] = 255;
            }
        }
        raster.setPixels(0, y, image.getWidth(), 1, pixels);
    }
    return result;
}
 
Example 9
Project: openjdk-jdk10   File: TestCompressionBI_BITFIELDS.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws IOException {
    // buffered image types listed below can be saved as BI_BITFIELDS BMP
    int[] types = {BufferedImage.TYPE_3BYTE_BGR,
                   BufferedImage.TYPE_USHORT_555_RGB,
                   BufferedImage.TYPE_USHORT_565_RGB,
                   BufferedImage.TYPE_BYTE_GRAY,
                   BufferedImage.TYPE_BYTE_BINARY,
                   BufferedImage.TYPE_BYTE_INDEXED,
                   BufferedImage.TYPE_INT_BGR,
                   BufferedImage.TYPE_INT_RGB};

    for (int i = 0; i < types.length; i++) {
        System.out.println("Test image " + types[i]);
        TestCompressionBI_BITFIELDS t = new TestCompressionBI_BITFIELDS();

        BufferedImage src =
            t.createTestImage(types[i]);
        System.out.println("Image for test: " + src);
        System.out.println("SampleModel: " + src.getSampleModel());

        BufferedImage dst = null;
        try {
            dst = t.writeAndRead(src);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }


        t.compareImages(src, dst);
    }
}
 
Example 10
Project: readySET   File: XORShitHi.java   View Source Code Vote up 5 votes
private static BufferedImage convertToGrayscale(BufferedImage img1) {
    BufferedImage image = new BufferedImage(img1.getWidth(), img1.getHeight(),
            BufferedImage.TYPE_BYTE_GRAY);
    Graphics g = image.getGraphics();
    g.drawImage(img1, 0, 0, null);
    g.dispose();

    return image;
}
 
Example 11
Project: kronometer   File: Utility.java   View Source Code Vote up 5 votes
public static BufferedImage matToBufferedImage(Mat matrix) {
    int cols = matrix.cols();
    int rows = matrix.rows();
    int elemSize = (int) matrix.elemSize();
    byte[] data = new byte[cols * rows * elemSize];
    int type;
    matrix.get(0, 0, data);
    switch (matrix.channels()) {
        case 1:
            type = BufferedImage.TYPE_BYTE_GRAY;
            break;
        case 3:
            type = BufferedImage.TYPE_3BYTE_BGR;
            // bgr to rgb  
            byte b;
            for (int i = 0; i < data.length; i = i + 3) {
                b = data[i];
                data[i] = data[i + 2];
                data[i + 2] = b;
            }
            break;
        default:
            return null;
    }
    BufferedImage bimg = new BufferedImage(cols, rows, type);
    bimg.getRaster().setDataElements(0, 0, cols, rows, data);
    return bimg;
}
 
Example 12
Project: imageio-jnr   File: TurboJpeg.java   View Source Code Vote up 5 votes
/** Decode the JPEG image in the input buffer into a BufferedImage.
 *
 * @param jpegData  JPEG data input buffer
 * @param info Information about the JPEG image in the buffer
 * @param size Target decompressed dimensions, must be among the available sizes (see {@link Info#getAvailableSizes()})
 * @return The decoded image
 * @throws TurboJpegException
 */
public BufferedImage decode(byte[] jpegData, Info info, Dimension size) throws TurboJpegException {
  Pointer codec = null;
  try {
    codec = lib.tjInitDecompress();
    int width = info.getWidth();
    int height = info.getHeight();
    if (size != null) {
      if (!info.getAvailableSizes().contains(size)) {
        throw new IllegalArgumentException(String.format(
            "Invalid size, must be one of %s", info.getAvailableSizes()));
      } else {
        width = size.width;
        height = size.height;
      }
    }
    boolean isGray = info.getSubsampling() == TJSAMP.TJSAMP_GRAY.intValue();
    int imgType;
    if (isGray) {
      imgType = BufferedImage.TYPE_BYTE_GRAY;
    } else {
      imgType = BufferedImage.TYPE_3BYTE_BGR;
    }
    BufferedImage img = new BufferedImage(width, height, imgType);
    // Wrap the underlying data buffer of the image with a ByteBuffer so we can pass it over the ABI
    ByteBuffer outBuf = ByteBuffer.wrap(((DataBufferByte) img.getRaster().getDataBuffer()).getData())
                                  .order(runtime.byteOrder());
    int rv = lib.tjDecompress2(
        codec, ByteBuffer.wrap(jpegData), jpegData.length, outBuf,
        width, isGray ? width : width * 3, height, isGray ? TJPF.TJPF_GRAY : TJPF.TJPF_BGR, 0);
    if (rv != 0) {
      LOG.error("Could not decompress JPEG (dimensions: {}x{}, gray: {})", width, height, isGray);
      throw new TurboJpegException(lib.tjGetErrorStr());
    }
    return img;
  } finally {
    if (codec != null && codec.address() != 0) lib.tjDestroy(codec);
  }
}
 
Example 13
Project: anagnostes   File: Normalizer.java   View Source Code Vote up 5 votes
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
	Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
	BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_BYTE_GRAY);
	Graphics2D g2d = dimg.createGraphics();
	g2d.drawImage(tmp, 0, 0, null);
	g2d.dispose();
	return dimg;
}
 
Example 14
Project: ocraft-s2client   File: ImageData.java   View Source Code Vote up 5 votes
private int tryGetImageType() {
    switch (bitsPerPixel) {
        case 1:
            return BufferedImage.TYPE_BYTE_BINARY;
        case 8:
            return BufferedImage.TYPE_BYTE_GRAY;
        case 32:
            return BufferedImage.TYPE_4BYTE_ABGR;
        default:
            throw new IllegalArgumentException(
                    format("Unsupported image type with bits per pixel [%d]. Expected {1, 8, 32}.", bitsPerPixel));
    }
}
 
Example 15
Project: AquamarineLake   File: DrawPanel.java   View Source Code Vote up 5 votes
public Image enhancedMatToBufferedImage(Mat m){
    int type = BufferedImage.TYPE_BYTE_GRAY;
    if ( m.channels() > 1 ) {
        type = BufferedImage.TYPE_3BYTE_BGR;
    }
    int bufferSize = m.channels()*m.cols()*m.rows();
    byte [] b = new byte[bufferSize];
    m.get(0,0,b); // get all the pixels
    BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
    final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    System.arraycopy(b, 0, targetPixels, 0, b.length);
    return image;

}
 
Example 16
Project: OpenJSharp   File: Destinations.java   View Source Code Vote up 5 votes
public static void init() {
    destroot = new Group.EnableSet(TestEnvironment.globaloptroot,
                                   "dest", "Output Destination Options");

    new Screen();
    new OffScreen();

    if (GraphicsTests.hasGraphics2D) {
        if (ImageTests.hasCompatImage) {
            compatimgdestroot =
                new Group.EnableSet(destroot, "compatimg",
                                    "Compatible Image Destinations");
            compatimgdestroot.setHorizontal();

            new CompatImg();
            new CompatImg(Transparency.OPAQUE);
            new CompatImg(Transparency.BITMASK);
            new CompatImg(Transparency.TRANSLUCENT);
        }

        if (ImageTests.hasVolatileImage) {
            new VolatileImg();
        }

        bufimgdestroot = new Group.EnableSet(destroot, "bufimg",
                                             "BufferedImage Destinations");

        new BufImg(BufferedImage.TYPE_INT_RGB);
        new BufImg(BufferedImage.TYPE_INT_ARGB);
        new BufImg(BufferedImage.TYPE_INT_ARGB_PRE);
        new BufImg(BufferedImage.TYPE_3BYTE_BGR);
        new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
        new BufImg(BufferedImage.TYPE_BYTE_GRAY);
        new CustomImg();
    }
}
 
Example 17
Project: Lunar   File: TestTile.java   View Source Code Vote up 4 votes
public TestTile(int width, int height) {
    super(new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY), TILE_COUNTER++);
}
 
Example 18
Project: openjdk-jdk10   File: PixelTests.java   View Source Code Vote up 4 votes
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 19
Project: openjdk-jdk10   File: CrashTest.java   View Source Code Vote up 4 votes
private static void testHugeImage(final int width, final int height)
    throws ArrayIndexOutOfBoundsException
{
    System.out.println("---\n" + "testHugeImage: "
        + "width=" + width + ", height=" + height);

    final BasicStroke stroke = createStroke(2.5f, false, 0);

    // size > 24bits (exceed both tile and buckets arrays)
    System.out.println("image size = " + width + " x "+height);

    final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

    final Graphics2D g2d = (Graphics2D) image.getGraphics();
    try {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

        g2d.setBackground(Color.WHITE);
        g2d.clearRect(0, 0, width, height);

        g2d.setStroke(stroke);
        g2d.setColor(Color.BLACK);

        final Path2D.Float path = new Path2D.Float(WIND_NON_ZERO, 32);
        path.moveTo(0, 0);
        path.lineTo(width, 0);
        path.lineTo(width, height);
        path.lineTo(0, height);
        path.lineTo(0, 0);

        final long start = System.nanoTime();

        g2d.draw(path);

        final long time = System.nanoTime() - start;

        System.out.println("paint: duration= " + (1e-6 * time) + " ms.");

        if (SAVE_IMAGE) {
            try {
                final File file = new File("CrashTest-huge-"
                    + width + "x" +height + ".bmp");

                System.out.println("Writing file: " + file.getAbsolutePath());
                ImageIO.write(image, "BMP", file);
            } catch (IOException ex) {
                System.out.println("Writing file failure:");
                ex.printStackTrace();
            }
        }
    } finally {
        g2d.dispose();
    }
}
 
Example 20
Project: AquamarineLake   File: DrawPanel.java   View Source Code Vote up 3 votes
public BufferedImage bufferedImage(Mat m) {


        int type = BufferedImage.TYPE_BYTE_GRAY;
        if (m.channels() > 1) {
            type = BufferedImage.TYPE_3BYTE_BGR;
        }
        BufferedImage image = new BufferedImage(m.cols(), m.rows(), type);

        m.get(0, 0, ((DataBufferByte)image.getRaster().getDataBuffer()).getData());
        return image;

    }