public void draw(BufferedImage buf) { WritableRaster dst = buf.getRaster(); blit(dst, bg.getRaster(), Coord.z); alphablit(dst, rmeter(sbars[0].getRaster(), lmax[0], max), mc[0]); alphablit( dst, lmeter(sbars[1].getRaster(), lmax[1], max), mc[1].sub(bars[1].getWidth() - 1, 0)); alphablit( dst, lmeter(sbars[2].getRaster(), lmax[2], max), mc[2].sub(bars[2].getWidth() - 1, 0)); alphablit(dst, rmeter(sbars[3].getRaster(), lmax[3], max), mc[3]); if (lfood != null) { double e = foodeff(lfood); alphablit(dst, rgmeter(lfood, e, 0), mc[0]); alphablit(dst, lgmeter(lfood, e, 1), mc[1].sub(bars[1].getWidth() - 1, 0)); alphablit(dst, lgmeter(lfood, e, 2), mc[2].sub(bars[1].getWidth() - 1, 0)); alphablit(dst, rgmeter(lfood, e, 3), mc[3]); } alphablit(dst, rmeter(bars[0].getRaster(), lev[0], max), mc[0]); alphablit(dst, lmeter(bars[1].getRaster(), lev[1], max), mc[1].sub(bars[1].getWidth() - 1, 0)); alphablit(dst, lmeter(bars[2].getRaster(), lev[2], max), mc[2].sub(bars[2].getWidth() - 1, 0)); alphablit(dst, rmeter(bars[3].getRaster(), lev[3], max), mc[3]); StringBuilder tbuf = new StringBuilder(); for (int i = 0; i < 4; i++) tbuf.append( String.format( "%s: %s/%s\n", rnm[i], Utils.fpformat(lev[i], 3, 1), Utils.fpformat(lmax[i], 3, 1))); tooltip = RichText.render(tbuf.toString(), 0).tex(); }
private BufferedImage windowRGB(BufferedImage srcImg, float windowLocation, float windowWidth) { BufferedImage destImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB); final int windowedImageBandValuesCount = 256; // for BufferedImage.TYPE_INT_RGB float scale = windowedImageBandValuesCount / windowWidth; float offset = (windowWidth / 2 - windowLocation) * scale; if (!srcImg.getColorModel().getColorSpace().isCS_sRGB()) { throw new IllegalArgumentException("source image must be RGB"); } Raster srcRaster = srcImg.getRaster(); if (srcRaster.getNumBands() != 3) { throw new IllegalArgumentException( "RGB source image must have three color bands, but has " + srcRaster.getNumBands() + "??"); } WritableRaster resultRaster = destImg.getRaster(); for (int x = 0; x < srcImg.getWidth(); x++) { for (int y = 0; y < srcImg.getHeight(); y++) { for (int band = 0; band < 3; band++) { int srcGrayValue = srcRaster.getSample(x, y, band); float destGrayValue = scale * srcGrayValue + offset; // clamp if (destGrayValue < 0) { destGrayValue = 0; } else if (destGrayValue >= windowedImageBandValuesCount) { destGrayValue = windowedImageBandValuesCount - 1; } resultRaster.setSample(x, y, band, destGrayValue); } } } return destImg; }
public static void main(String[] args) { try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); File input = new File("traffic_signal.jpg"); BufferedImage image = ImageIO.read(input); byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3); mat.put(0, 0, data); Mat mat1 = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1); Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY); byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int) (mat1.elemSize())]; mat1.get(0, 0, data1); BufferedImage image1 = new BufferedImage(mat1.cols(), mat1.rows(), BufferedImage.TYPE_BYTE_GRAY); image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1); File ouptut = new File("output\\grayscale_" + new Date().getTime() + ".jpg"); ImageIO.write(image1, "jpg", ouptut); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } }
public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); int type = src.getType(); WritableRaster srcRaster = src.getRaster(); if (dst == null) dst = createCompatibleDestImage(src, null); WritableRaster dstRaster = dst.getRaster(); setDimensions(width, height); int[] inPixels = new int[width]; for (int y = 0; y < height; y++) { // We try to avoid calling getRGB on images as it causes them to become unmanaged, causing // horrible performance problems. if (type == BufferedImage.TYPE_INT_ARGB) { srcRaster.getDataElements(0, y, width, 1, inPixels); for (int x = 0; x < width; x++) inPixels[x] = filterRGB(x, y, inPixels[x]); dstRaster.setDataElements(0, y, width, 1, inPixels); } else { src.getRGB(0, y, width, 1, inPixels, 0, width); for (int x = 0; x < width; x++) inPixels[x] = filterRGB(x, y, inPixels[x]); dst.setRGB(0, y, width, 1, inPixels, 0, width); } } return dst; }
/** * _more_ * * @param image_data _more_ */ private void createBufferedImage(float image_data[][]) { WritableRaster raster = null; int num_bands = 0; if (null != preview_image) { preview_image.getSampleModel().getNumBands(); } if ((null == preview_image) || (image_data.length != num_bands)) { if (image_data.length == 1) { preview_image = new BufferedImage(subSampledPixels, subSampledScans, BufferedImage.TYPE_BYTE_GRAY); } else { preview_image = new BufferedImage(subSampledPixels, subSampledScans, BufferedImage.TYPE_3BYTE_BGR); } DataBufferFloat dbuf = new DataBufferFloat(image_data, subSampledPixels * subSampledScans * image_data.length); SampleModel sampleModel = new BandedSampleModel(0, subSampledPixels, subSampledScans, image_data.length); raster = Raster.createWritableRaster(sampleModel, dbuf, new Point(0, 0)); preview_image.setData(raster); } else if (1 == num_bands) { preview_image .getRaster() .setDataElements( 0, 0, preview_image.getWidth(), preview_image.getHeight(), image_data[0]); } else if (3 == num_bands) { preview_image .getRaster() .setDataElements(0, 0, preview_image.getWidth(), preview_image.getHeight(), image_data); } }
protected BufferedImage scalingIfNeed( BufferedImage image, int dstWidth, int dstHeight, boolean needAlpha) { if (dstHeight > 0 && dstWidth > 0 && (image.getHeight() != dstHeight || image.getWidth() != dstWidth)) { Image scaled = image.getScaledInstance(dstWidth, dstHeight, Image.SCALE_SMOOTH); if (needAlpha && image.getColorModel().hasAlpha()) { return toBufferedImage(scaled, BufferedImage.TYPE_4BYTE_ABGR); } else { if (image.getRaster().getNumDataElements() == 1) return toBufferedImage(scaled, BufferedImage.TYPE_BYTE_GRAY); else return toBufferedImage(scaled, BufferedImage.TYPE_3BYTE_BGR); } } else { if (image.getType() == BufferedImage.TYPE_4BYTE_ABGR || image.getType() == BufferedImage.TYPE_3BYTE_BGR) { return image; } else if (needAlpha && image.getColorModel().hasAlpha()) { return toBufferedImage(image, BufferedImage.TYPE_4BYTE_ABGR); } else { if (image.getRaster().getNumDataElements() == 1) return toBufferedImage(image, BufferedImage.TYPE_BYTE_GRAY); else return toBufferedImage(image, BufferedImage.TYPE_3BYTE_BGR); } } }
@NotNull public static Icon colorize(@NotNull final Icon source, @NotNull Color color, boolean keepGray) { float[] base = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); final BufferedImage image = UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT); final Graphics2D g = image.createGraphics(); source.paintIcon(null, g, 0, 0); g.dispose(); final BufferedImage img = UIUtil.createImage(source.getIconWidth(), source.getIconHeight(), Transparency.TRANSLUCENT); int[] rgba = new int[4]; float[] hsb = new float[3]; for (int y = 0; y < image.getRaster().getHeight(); y++) { for (int x = 0; x < image.getRaster().getWidth(); x++) { image.getRaster().getPixel(x, y, rgba); if (rgba[3] != 0) { Color.RGBtoHSB(rgba[0], rgba[1], rgba[2], hsb); int rgb = Color.HSBtoRGB(base[0], base[1] * (keepGray ? hsb[1] : 1f), base[2] * hsb[2]); img.getRaster() .setPixel(x, y, new int[] {rgb >> 16 & 0xff, rgb >> 8 & 0xff, rgb & 0xff, rgba[3]}); } } } return createImageIcon(img); }
public synchronized java.awt.image.BufferedImage getSynthesizedImage() { if (synthesizedImage != null) { return synthesizedImage; } ; if (foregroundImage != null) { formAndGetConnectedGraphs(); int vectorLength = imageWidth * imageHeight; boolean[] bitMask = new boolean[vectorLength]; for (int n = 0; n < graphs.length; n++) { graphs[n].enablePixels(recentFrameNumber, bitMask, imageWidth, imageHeight, tracks); } ; java.awt.image.BufferedImage extractedImage = new java.awt.image.BufferedImage( imageWidth, imageHeight, java.awt.image.BufferedImage.TYPE_4BYTE_ABGR); WritableRaster raster = extractedImage.getRaster(); raster.setDataElements(0, 0, foregroundImage.getRaster()); java.awt.image.BufferedImage resultImage = applyMaskAndCreateImage(extractedImage, bitMask); synthesizedImage = resultImage; return synthesizedImage; } else { return null; } }
private boolean newImage(BufferedImage tmpImage) { Boolean iguales = true; // Si es la primer imagen if (lastBufferedImage == null) { // Devuelvo true return true; } // Obtengo los buffers de las imágenes DataBuffer newImageDataBuffer = tmpImage.getRaster().getDataBuffer(); DataBuffer lastImageDataBuffer = lastBufferedImage.getRaster().getDataBuffer(); // Obtengo los tipos de los buffers. DataBufferInt newImageDBAsDBInt = (DataBufferInt) newImageDataBuffer; DataBufferInt lastImageDBAsDBInt = (DataBufferInt) lastImageDataBuffer; // Armo arreglos de ints con la información de los buffers for (int bank = 0; bank < newImageDBAsDBInt.getNumBanks(); bank++) { int[] nueva = newImageDBAsDBInt.getData(bank); int[] anterior = lastImageDBAsDBInt.getData(bank); // si la información es la misma if (Arrays.equals(nueva, anterior) == true) { // las imágenes son iguales y devuelvo false ya que NO debo enviarla iguales = false; } } // Si las imágenes son distintas, devuelvo true ya que debo enviarla. return iguales; }
public void releaseSound(String filepath, String destpath, int Threshold) { // 过滤背景色进行黑白二值化处理 try { BufferedImage bi = ImageIO.read(new File(filepath)); int width = bi.getWidth(); int height = bi.getHeight(); BufferedImage bi2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Raster raster = bi.getRaster(); WritableRaster wr = bi2.getRaster(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { int[] a = new int[4]; raster.getPixel(i, j, a); // System.out.println("("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+")"); if ((a[0] + a[1] + a[2]) / 3 > Threshold) { a[0] = 255; a[1] = 255; a[2] = 255; a[3] = 255; wr.setPixel(i, j, a); } else { a[0] = 0; a[1] = 0; a[2] = 0; a[3] = 255; wr.setPixel(i, j, a); } } } ImageIO.write(bi2, "PNG", new File(destpath)); // ImageIO.write(bi, "PNG", new File(destpath)); } catch (IOException e) { e.printStackTrace(); } }
public static BufferedImage matte(BufferedImage source, Color matteColor) { final int width = source.getWidth(); final int height = source.getHeight(); // A workaround for possibly different custom image types we can get: // draw a copy of the image final BufferedImage sourceConverted = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED); sourceConverted.getGraphics().drawImage(source, 0, 0, null); final BufferedImage matted = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED); final BufferedImage matte = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED); final int matteRgb = matteColor.getRGB(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { matte.setRGB(x, y, matteRgb); } } CompositeContext context = AlphaComposite.DstOver.createContext( matte.getColorModel(), sourceConverted.getColorModel(), null); context.compose(matte.getRaster(), sourceConverted.getRaster(), matted.getRaster()); return sourceConverted; }
private BufferedImage windowMonochrome( ImageListViewCell displayedCell, BufferedImage srcImg, float windowLocation, float windowWidth) { BufferedImage destImg = new BufferedImage(srcImg.getWidth(), srcImg.getHeight(), BufferedImage.TYPE_INT_RGB); boolean isSigned = false; int minValue = 0; { // hack: try to determine signedness and minValue from DICOM metadata if available -- // the BufferedImage's metadata don't contain that information reliably. // Only works for some special cases ImageListViewModelElement elt = displayedCell.getDisplayedModelElement(); if (elt instanceof DicomImageListViewModelElement) { DicomImageListViewModelElement delt = (DicomImageListViewModelElement) elt; DicomObject imgMetadata = delt.getDicomImageMetaData(); int bitsAllocated = imgMetadata.getInt(Tag.BitsAllocated); isSigned = (1 == imgMetadata.getInt(Tag.PixelRepresentation)); if (isSigned && (bitsAllocated > 0)) { minValue = -(1 << (bitsAllocated - 1)); } } } final int windowedImageGrayscalesCount = 256; // for BufferedImage.TYPE_INT_RGB float scale = windowedImageGrayscalesCount / windowWidth; float offset = (windowWidth / 2 - windowLocation) * scale; if (!(srcImg.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_GRAY)) { throw new IllegalArgumentException("source image must be grayscales"); } Raster srcRaster = srcImg.getRaster(); if (srcRaster.getNumBands() != 1) { throw new IllegalArgumentException( "grayscale source image must have one color band, but has " + srcRaster.getNumBands() + "??"); } WritableRaster resultRaster = destImg.getRaster(); for (int x = 0; x < srcImg.getWidth(); x++) { for (int y = 0; y < srcImg.getHeight(); y++) { int srcGrayValue = srcRaster.getSample(x, y, 0); if (isSigned) { srcGrayValue = (int) (short) srcGrayValue; // will only work for 16-bit signed... } float destGrayValue = scale * srcGrayValue + offset; // clamp if (destGrayValue < 0) { destGrayValue = 0; } else if (destGrayValue >= windowedImageGrayscalesCount) { destGrayValue = windowedImageGrayscalesCount - 1; } resultRaster.setSample(x, y, 0, destGrayValue); resultRaster.setSample(x, y, 1, destGrayValue); resultRaster.setSample(x, y, 2, destGrayValue); } } return destImg; }
public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); int type = src.getType(); WritableRaster srcRaster = src.getRaster(); originalSpace = new Rectangle(0, 0, width, height); transformedSpace = new Rectangle(0, 0, width, height); transformSpace(transformedSpace); if (dst == null) { ColorModel dstCM = src.getColorModel(); dst = new BufferedImage( dstCM, dstCM.createCompatibleWritableRaster(transformedSpace.width, transformedSpace.height), dstCM.isAlphaPremultiplied(), null); } WritableRaster dstRaster = dst.getRaster(); int[] inPixels = getRGB(src, 0, 0, width, height, null); inPixels = filterPixels(width, height, inPixels, transformedSpace); setRGB(dst, 0, 0, transformedSpace.width, transformedSpace.height, inPixels); return dst; }
/** * Checks to see if the BufferedImage has the same intensity values as the ImageUInt8 * * @param imgA BufferedImage * @param imgB ImageUInt8 */ public static void checkEquals(BufferedImage imgA, ImageInt16 imgB) { if (imgA.getRaster() instanceof ByteInterleavedRaster && imgA.getType() != BufferedImage.TYPE_BYTE_INDEXED) { ByteInterleavedRaster raster = (ByteInterleavedRaster) imgA.getRaster(); if (raster.getNumBands() == 1) { int strideA = raster.getScanlineStride(); int offsetA = raster.getDataOffset(0) - raster.getNumBands() + 1; // handle a special case where the RGB conversion is screwed for (int i = 0; i < imgA.getHeight(); i++) { for (int j = 0; j < imgA.getWidth(); j++) { int valB = imgB.get(j, i); int valA = raster.getDataStorage()[offsetA + i * strideA + j]; if (!imgB.getTypeInfo().isSigned()) valA &= 0xFFFF; if (valA != valB) throw new RuntimeException("Images are not equal: " + valA + " " + valB); } } return; } } else if (imgA.getRaster() instanceof ShortInterleavedRaster) { ShortInterleavedRaster raster = (ShortInterleavedRaster) imgA.getRaster(); if (raster.getNumBands() == 1) { int strideA = raster.getScanlineStride(); int offsetA = raster.getDataOffset(0) - raster.getNumBands() + 1; // handle a special case where the RGB conversion is screwed for (int i = 0; i < imgA.getHeight(); i++) { for (int j = 0; j < imgA.getWidth(); j++) { int valB = imgB.get(j, i); int valA = raster.getDataStorage()[offsetA + i * strideA + j]; if (!imgB.getTypeInfo().isSigned()) valA &= 0xFFFF; if (valA != valB) throw new RuntimeException("Images are not equal: " + valA + " " + valB); } } } } else { for (int y = 0; y < imgA.getHeight(); y++) { for (int x = 0; x < imgA.getWidth(); x++) { int rgb = imgA.getRGB(x, y); int gray = ((((rgb >>> 16) & 0xFF) + ((rgb >>> 8) & 0xFF) + (rgb & 0xFF)) / 3); int grayB = imgB.get(x, y); if (!imgB.getTypeInfo().isSigned()) gray &= 0xFFFF; if (Math.abs(gray - grayB) != 0) { throw new RuntimeException( "images are not equal: (" + x + " , " + y + ") A = " + gray + " B = " + grayB); } } } } }
public boolean checkhit(Coord c) { if (!c.isect(Coord.z, sz)) { return (false); } if (up.getRaster().getNumBands() < 4) { return (true); } return (up.getRaster().getSample(c.x, c.y, 3) >= 128); }
/** * Builds a new BufferedImage that is the difference between the two input images * * @param ref the reference bitmap * @param gen the newly generated bitmap * @return the diff bitmap */ public static BufferedImage buildDiffImage(BufferedImage ref, BufferedImage gen) { BufferedImage diff = new BufferedImage(ref.getWidth(), ref.getHeight(), BufferedImage.TYPE_INT_ARGB); WritableRaster refWR = ref.getRaster(); WritableRaster genWR = gen.getRaster(); WritableRaster dstWR = diff.getRaster(); boolean refPre = ref.isAlphaPremultiplied(); if (!refPre) { ColorModel cm = ref.getColorModel(); cm = GraphicsUtil.coerceData(refWR, cm, true); ref = new BufferedImage(cm, refWR, true, null); } boolean genPre = gen.isAlphaPremultiplied(); if (!genPre) { ColorModel cm = gen.getColorModel(); cm = GraphicsUtil.coerceData(genWR, cm, true); gen = new BufferedImage(cm, genWR, true, null); } int w = ref.getWidth(); int h = ref.getHeight(); int y, i, val; int[] refPix = null; int[] genPix = null; for (y = 0; y < h; y++) { refPix = refWR.getPixels(0, y, w, 1, refPix); genPix = genWR.getPixels(0, y, w, 1, genPix); for (i = 0; i < refPix.length; i++) { // val = ((genPix[i] - refPix[i]) * 5) + 128; val = ((refPix[i] - genPix[i]) * 10) + 128; if ((val & 0xFFFFFF00) != 0) { if ((val & 0x80000000) != 0) { val = 0; } else { val = 255; } } genPix[i] = val; } dstWR.setPixels(0, y, w, 1, genPix); } if (!genPre) { ColorModel cm = gen.getColorModel(); cm = GraphicsUtil.coerceData(genWR, cm, false); } if (!refPre) { ColorModel cm = ref.getColorModel(); cm = GraphicsUtil.coerceData(refWR, cm, false); } return diff; }
public static ArthurImage multiply(ArthurImage one, ArthurImage two) { BufferedImage image = JavaImageMath.clone(one.bf); BufferedImage image2 = JavaImageMath.clone(two.bf); WritableRaster r1 = image.getRaster(); WritableRaster r2 = image2.getRaster(); int newWidth = Math.max(r1.getWidth(), r2.getWidth()); int newHeight = Math.max(r1.getHeight(), r2.getHeight()); BufferedImage collage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); WritableRaster raster = collage.getRaster(); int[] p1 = new int[3]; int[] p2 = new int[3]; int[] pixelArray = new int[3]; for (int y = 0; y < newHeight; y++) { for (int x = 0; x < newWidth; x++) { p1 = null; p2 = null; if (x < r1.getWidth() && y < r1.getHeight()) { p1 = r1.getPixel(x, y, p1); } if (x < r2.getWidth() && y < r2.getHeight()) { p2 = r2.getPixel(x, y, p2); } for (int i = 0; i < 3; i++) { if (p1 == null && p2 == null) { pixelArray[i] = 0; } else if (p1 == null && p2 != null) { pixelArray[i] = p2[i]; } else if (p1 != null && p2 == null) { pixelArray[i] = p1[i]; } else { pixelArray[i] = (int) ((p1[i] + p2[i]) / 2); } } raster.setPixel(x, y, pixelArray); } } // save image String outputFn = one.filename.substring(0, one.filename.indexOf(".jpg")) + "X" + // filename can't contain the / or *characters; decide later two.filename.substring(0, two.filename.indexOf(".jpg")) + counter + ".jpg"; counter++; return new ArthurImage(collage, outputFn); }
static ImageData convertToSWT(BufferedImage bufferedImage) { if (bufferedImage.getColorModel() instanceof DirectColorModel) { DirectColorModel colorModel = (DirectColorModel) bufferedImage.getColorModel(); PaletteData palette = new PaletteData( colorModel.getRedMask(), colorModel.getGreenMask(), colorModel.getBlueMask()); ImageData data = new ImageData( bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette); WritableRaster raster = bufferedImage.getRaster(); int[] pixelArray = new int[3]; for (int y = 0; y < data.height; y++) { for (int x = 0; x < data.width; x++) { raster.getPixel(x, y, pixelArray); int pixel = palette.getPixel(new RGB(pixelArray[0], pixelArray[1], pixelArray[2])); data.setPixel(x, y, pixel); } } return data; } else if (bufferedImage.getColorModel() instanceof IndexColorModel) { IndexColorModel colorModel = (IndexColorModel) bufferedImage.getColorModel(); int size = colorModel.getMapSize(); byte[] reds = new byte[size]; byte[] greens = new byte[size]; byte[] blues = new byte[size]; colorModel.getReds(reds); colorModel.getGreens(greens); colorModel.getBlues(blues); RGB[] rgbs = new RGB[size]; for (int i = 0; i < rgbs.length; i++) { rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF, blues[i] & 0xFF); } PaletteData palette = new PaletteData(rgbs); ImageData data = new ImageData( bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette); data.transparentPixel = colorModel.getTransparentPixel(); WritableRaster raster = bufferedImage.getRaster(); int[] pixelArray = new int[1]; for (int y = 0; y < data.height; y++) { for (int x = 0; x < data.width; x++) { raster.getPixel(x, y, pixelArray); data.setPixel(x, y, pixelArray[0]); } } return data; } return null; }
public void write(IIOMetadata streamMetadata, IIOImage img, ImageWriteParam param) throws IOException { ImageOutputStream out = (ImageOutputStream) getOutput(); if (!(img.getRenderedImage() instanceof BufferedImage)) { throw new IOException(getClass().getName() + "write:\nCan only write BufferedImage objects"); } BufferedImage image = (BufferedImage) img.getRenderedImage(); int width = image.getWidth(); int height = image.getHeight(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JFIFOutputStream os; if (image.getType() == BufferedImage.TYPE_BYTE_GRAY) { // one component; grey scale os = new JFIFOutputStream(baos, false, height, width); // SOF:start of frame WritableRaster raster = image.getRaster(); DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer(); byte[] imgdata = (byte[]) buffer.getData(); os.write(imgdata); os.close(); // EOF: end of frame } else if (image.getType() == BufferedImage.TYPE_INT_RGB) { // three components; YCbCr os = new JFIFOutputStream(baos, true, height, width); // SOF:start of frame WritableRaster raster = image.getRaster(); DataBufferInt buffer = (DataBufferInt) raster.getDataBuffer(); int[] imgdata = (int[]) buffer.getData(); os.write(imgdata); os.close(); // EOF: end of frame } else { // three components; YCbCr os = new JFIFOutputStream(baos, true, height, width); // SOF:start of frame for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { os.write(image.getRGB(x, y)); } } os.close(); // EOF: end of frame } out.write(baos.toByteArray()); // write to image stream } catch (Exception e) { e.printStackTrace(); throw new IOException( getClass().getName() + ".write:\n\tCould not write image due to :\n\t" + e.getMessage()); } }
/** * Creates a new Scale2x object. The new object will scale images of the specified size to images * that are twice as large.<br> * * @param width The width of the images to be scaled * @param height The height of the images to be scaled */ public Scale2x(int width, int height) { this.width = width; this.height = height; // A border of one pixel in each direction, and one down, to avoid if statements in the scale // loop sourceImage = new BufferedImage(width + 2, height + 3, BufferedImage.TYPE_INT_RGB); DataBufferInt sourceDataBuffer = (DataBufferInt) sourceImage.getRaster().getDataBuffer(); sourcePixels = sourceDataBuffer.getData(); sourceGraphics = sourceImage.getGraphics(); targetImage = new BufferedImage(width * 2, height * 2, BufferedImage.TYPE_INT_RGB); DataBufferInt targetDataBuffer = (DataBufferInt) targetImage.getRaster().getDataBuffer(); targetPixels = targetDataBuffer.getData(); }
public void update() { img.getRaster().setDataElements(0, 0, d.width, d.height, pixels); // img.setRGB(0, 0, d.width, d.height, pixels,0,d.width); // Image img = Toolkit.getDefaultToolkit().createImage(new // MemoryImageSource(d.width,d.height,pixels,0,d.width)); // System.out.println(" image type "+(img instanceof VolatileImage)); }
private static double[] getHist(ImageData queryImage) throws IOException { BufferedImage image = queryImage.getImage(); int imHeight = image.getHeight(); int imWidth = image.getWidth(); double[] bins = new double[dim * dim * dim]; int step = 256 / dim; Raster raster = image.getRaster(); for (int i = 0; i < imWidth; i++) { for (int j = 0; j < imHeight; j++) { // rgb->ycrcb int r = raster.getSample(i, j, 0); int g = raster.getSample(i, j, 1); int b = raster.getSample(i, j, 2); // Changed Codes. int y = (int) (0 + 0.299 * r + 0.587 * g + 0.114 * b); int cb = (int) (128 - 0.16874 * r - 0.33126 * g + 0.50000 * b); int cr = (int) (128 + 0.50000 * r - 0.41869 * g - 0.08131 * b); int ybin = y / step; int cbbin = cb / step; int crbin = cr / step; // Changed Codes. bins[ybin * dim * dim + cbbin * dim + crbin]++; } } // Changed Codes. for (int i = 0; i < dim * dim * dim; i++) { bins[i] = bins[i] / (imHeight * imWidth); } return bins; }
public static void main(String[] args) throws DocumentException, MalformedURLException, IOException { BufferedImage image = ImageIO.read(imageFile); BufferedImage bi = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); ColorConvertOp xformOp = new ColorConvertOp(null); xformOp.filter(image, bi); // bi.setData(icon.getData()); WritableRaster raster = bi.getRaster(); DataBufferInt data = (DataBufferInt) raster.getDataBuffer(); int[] intData = data.getData(); ByteBuffer byteBuffer = ByteBuffer.allocate(intData.length * 4); IntBuffer intBuffer = byteBuffer.asIntBuffer(); intBuffer.put(intData); byte[] array = byteBuffer.array(); System.out.println(Hex.encodeHex(array)); }
/** * Helper function to convert a Mat into a BufferedImage. Taken from * http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui Author: 'Lucky Luke' * * @param matrix Mat of type CV_8UC3 or CV_8UC1 * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY */ private 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 image = new BufferedImage(cols, rows, type); image.getRaster().setDataElements(0, 0, cols, rows, data); return image; }
/** * The <code>extractFeature(MediaContent)</code> class loads the media content, convert it to HMMD * color space and executes the CSD extraction and quantization. * * @param image the image to be analyzed. * @throws Exception in some cases ... */ public void extractFeature(BufferedImage image) throws Exception { // load image to BufferedImage double height = image.getHeight(); double width = image.getWidth(); int temp[][] = new int[(int) height - 1][(int) width - 1]; // if (width > height) { // System.out.println("\nExit - vizir bug: file unsupported -> // MediaFrame.getPixelAt"); // System.exit(0); // } int ir[][] = temp; int ig[][] = temp; int ib[][] = temp; int iH[][] = temp; int iMax[][] = temp; int iMin[][] = temp; int iDiff[][] = temp; int iSum[][] = temp; // convert BufferedImage to double int array for every RGB color // ant then covert RGB values into HMMD WritableRaster raster = image.getRaster(); int[] pixel = new int[3]; for (int ch = 0; ch < height - 1; ch++) { // row for (int cw = 0; cw < width - 1; cw++) { // column raster.getPixel(cw, ch, pixel); ir[ch][cw] = pixel[0]; // RED ig[ch][cw] = pixel[1]; // GREEN ib[ch][cw] = pixel[2]; // BLUE int[] tempHMMD = RGB2HMMD(ir[ch][cw], ig[ch][cw], ib[ch][cw]); iH[ch][cw] = tempHMMD[0]; // H iMax[ch][cw] = tempHMMD[1]; // Max iMin[ch][cw] = tempHMMD[2]; // Min iDiff[ch][cw] = tempHMMD[3]; // Diff iSum[ch][cw] = tempHMMD[4]; // Sum } } ColorHistogram = HMMDColorStuctureExtraction( iH, iMax, iMin, iDiff, iSum, (int) height, (int) width); // extract HMMD colors and make histogram // if ( quantizationLevels != 256 ) ColorHistogram = reQuantization(ColorHistogram); // // requantize and normalize histogram to 0-255 range ColorHistogram = reQuantization(ColorHistogram); }
/** * Save onscreen image to file - suffix must be png, jpg, or gif. * * @param filename the name of the file with one of the required suffixes */ public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel( cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
/** * Writes the data for this segment to the stream in valid JPEG format. The length written takes * the thumbnail width and height into account. If necessary, the thumbnail is clipped to 255 x * 255 and a warning is sent to the writer argument. Progress updates are sent to the writer * argument. */ void write(ImageOutputStream ios, BufferedImage thumb, JPEGImageWriter writer) throws IOException { int thumbWidth = 0; int thumbHeight = 0; int thumbLength = 0; int[] thumbData = null; if (thumb != null) { // Clip if necessary and get the data in thumbData thumbWidth = thumb.getWidth(); thumbHeight = thumb.getHeight(); if ((thumbWidth > MAX_THUMB_WIDTH) || (thumbHeight > MAX_THUMB_HEIGHT)) { writer.warningOccurred(JPEGImageWriter.WARNING_THUMB_CLIPPED); } thumbWidth = Math.min(thumbWidth, MAX_THUMB_WIDTH); thumbHeight = Math.min(thumbHeight, MAX_THUMB_HEIGHT); thumbData = thumb.getRaster().getPixels(0, 0, thumbWidth, thumbHeight, (int[]) null); thumbLength = thumbData.length; } length = DATA_SIZE + LENGTH_SIZE + thumbLength; writeTag(ios); byte[] id = {0x4A, 0x46, 0x49, 0x46, 0x00}; ios.write(id); ios.write(majorVersion); ios.write(minorVersion); ios.write(resUnits); write2bytes(ios, Xdensity); write2bytes(ios, Ydensity); ios.write(thumbWidth); ios.write(thumbHeight); if (thumbData != null) { writer.thumbnailStarted(0); writeThumbnailData(ios, thumbData, writer); writer.thumbnailComplete(); } }
/** * internal use - get buffer from image * * @param scaledImage * @param deviceXSize * @param deviceYSize * @return */ private static int[] getPixelsFromImage( BufferedImage scaledImage, int deviceXSize, int deviceYSize) { // painfull slow! // return scaledImage.getRGB(0, 0, deviceXSize, deviceYSize, null, 0, deviceXSize); DataBufferInt buf = (DataBufferInt) scaledImage.getRaster().getDataBuffer(); return buf.getData(); }
private float getComplexity(BufferedImage img) { // Uses its own resizing method to remove color in the same step BufferedImage sml = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_BYTE_GRAY); sml.getGraphics().drawImage(img, 0, 0, SIZE, SIZE, null); float ret = 0; int w = sml.getWidth(); int h = sml.getHeight(); Kernel laplace = new Kernel(3, 3, new float[] {1, 1, 1, 1, -8, 1, 1, 1, 1}); ConvolveOp filter = new ConvolveOp(laplace); BufferedImage dest = filter.createCompatibleDestImage(sml, null); filter.filter(sml, dest); WritableRaster data = dest.getRaster(); int[] pixels = data.getPixels(0, 0, w, h, new int[w * h]); int sum = 0; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int temp = pixels[i + j * w]; sum += temp; } } ret = (float) sum / (w * h * 256); if (ret < 0.01) { ret = 1; } return ret; }
public void extract(BufferedImage image) { histogram = new double[18]; double[] directionality; ColorConvertOp op = new ColorConvertOp( image.getColorModel().getColorSpace(), ColorSpace.getInstance(ColorSpace.CS_GRAY), new RenderingHints( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY)); BufferedImage bimg = op.filter(image, null); bimg = ImageUtils.scaleImage(bimg, MAX_IMG_HEIGHT); Raster raster = bimg.getRaster(); int[] tmp = new int[3]; this.grayScales = new int[raster.getWidth()][raster.getHeight()]; for (int i = 0; i < raster.getWidth(); i++) { for (int j = 0; j < raster.getHeight(); j++) { raster.getPixel(i, j, tmp); this.grayScales[i][j] = tmp[0]; } } imgWidth = bimg.getWidth(); imgHeight = bimg.getHeight(); histogram[0] = this.coarseness(bimg.getWidth(), bimg.getHeight()); histogram[1] = this.contrast(); directionality = this.directionality(); for (int i = 2; i < histogram.length; i++) { histogram[i] = directionality[i - 2]; } }