List of usage examples for java.awt.image BufferedImage getRaster
public WritableRaster getRaster()
From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java
public static String getPixelValues(SourceImage sImg, int frameNum) { int signMask = 0; int signBit = 0; BufferedImage src = sImg.getBufferedImage(frameNum); if (sImg.isSigned()) { // the source image will already have been sign extended to the data type size // so we don't need to worry about other than exactly 8 and 16 bits if (src.getSampleModel().getDataType() == DataBuffer.TYPE_BYTE) { signBit = 0x0080;/*from w ww . ja va 2 s . c om*/ signMask = 0xffffff80; } else { // assume short or ushort signBit = 0x8000; signMask = 0xffff8000; } } double[] storedPixelValueArray; if (src.getRaster().getDataBuffer() instanceof DataBufferFloat) { float[] storedPixelValues = src.getSampleModel().getPixels(0, 0, src.getWidth(), src.getHeight(), (float[]) null, src.getRaster().getDataBuffer()); //copy to double array storedPixelValueArray = new double[storedPixelValues.length]; for (int i = 0; i < storedPixelValues.length; i++) { storedPixelValueArray[i] = storedPixelValues[i]; } } else if (src.getRaster().getDataBuffer() instanceof DataBufferDouble) { double[] storedPixelValues = src.getSampleModel().getPixels(0, 0, src.getWidth(), src.getHeight(), (double[]) null, src.getRaster().getDataBuffer()); storedPixelValueArray = storedPixelValues; } else { int[] storedPixelValues = src.getSampleModel().getPixels(0, 0, src.getWidth(), src.getHeight(), (int[]) null, src.getRaster().getDataBuffer()); int storedPixelValueInt = 0; //copy to double array storedPixelValueArray = new double[storedPixelValues.length]; for (int i = 0; i < storedPixelValues.length; i++) { storedPixelValueInt = storedPixelValues[i]; if (sImg.isSigned() && (storedPixelValueInt & signBit) != 0) { storedPixelValueInt |= signMask; // sign extend } storedPixelValueArray[i] = storedPixelValueInt; } } return JSON.toString(storedPixelValueArray); }
From source file:com.neophob.sematrix.core.generator.Textwriter.java
/** * create image.// w ww. j ava 2 s .c o m * * @param text the text */ public void createTextImage(String text) { //only load if needed if (StringUtils.equals(text, this.text)) { return; } this.text = text; BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = img.createGraphics(); FontRenderContext frc = g2.getFontRenderContext(); TextLayout layout = new TextLayout(text, font, frc); Rectangle2D rect = layout.getBounds(); int h = (int) (0.5f + rect.getHeight()); //head and tailing space maxXPos = (int) (0.5f + rect.getWidth()) + 2 * internalBufferXSize; int ypos = internalBufferYSize - (internalBufferYSize - h) / 2; img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_BYTE_GRAY); g2 = img.createGraphics(); g2.setColor(new Color(128)); g2.setFont(font); g2.setClip(0, 0, maxXPos, internalBufferYSize); g2.drawString(text, internalBufferXSize, ypos); DataBufferByte dbi = (DataBufferByte) img.getRaster().getDataBuffer(); byte[] textBuffer = dbi.getData(); g2.dispose(); xofs = 0; textAsImage = new int[maxXPos * internalBufferYSize]; for (int i = 0; i < textAsImage.length; i++) { if (textBuffer[i] > 10) { textAsImage[i] = 127; } else { textAsImage[i] = 0; } } //clear internalbuffer Arrays.fill(this.internalBuffer, 0); }
From source file:de.fhg.igd.swingrcp.SwingRCPUtilities.java
/** * Convert a {@link BufferedImage} to a SWT Image. * /* w w w .j a va2 s. c o m*/ * {@link "http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet156.java?view=co"} * * @param bufferedImage the AWT {@link BufferedImage} * @return the SWT {@link ImageData} */ public 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); for (int y = 0; y < data.height; y++) { for (int x = 0; x < data.width; x++) { int rgb = bufferedImage.getRGB(x, y); int pixel = palette.getPixel(new RGB((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF)); data.setPixel(x, y, pixel); // also set the alpha value (ST) data.setAlpha(x, y, colorModel.getAlpha(rgb)); } } 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; }
From source file:org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject.java
private BufferedImage applyMask(BufferedImage image, BufferedImage mask, boolean isSoft) throws IOException { if (mask == null) { return image; }//from w w w.ja v a2 s. co m int width = image.getWidth(); int height = image.getHeight(); // scale mask to fit image, or image to fit mask, whichever is larger if (mask.getWidth() < width || mask.getHeight() < height) { mask = scaleImage(mask, width, height); } else if (mask.getWidth() > width || mask.getHeight() > height) { width = mask.getWidth(); height = mask.getHeight(); image = scaleImage(image, width, height); } // compose to ARGB BufferedImage masked = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); WritableRaster src = image.getRaster(); WritableRaster dest = masked.getRaster(); WritableRaster alpha = mask.getRaster(); float[] rgb = new float[4]; float[] rgba = new float[4]; float[] alphaPixel = null; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { src.getPixel(x, y, rgb); rgba[0] = rgb[0]; rgba[1] = rgb[1]; rgba[2] = rgb[2]; alphaPixel = alpha.getPixel(x, y, alphaPixel); if (isSoft) { rgba[3] = alphaPixel[0]; } else { rgba[3] = 255 - alphaPixel[0]; } dest.setPixel(x, y, rgba); } } return masked; }
From source file:org.csa.rstb.polarimetric.rcp.toolviews.HaAlphaPlotPanel.java
@Override protected void updateChartData() { final ChartPagePanel chartPanel = this; final RasterDataNode rasterX = getRaster(X_VAR); final RasterDataNode rasterY = getRaster(Y_VAR); if (rasterX == null || rasterY == null) { return;//from w w w . j ava 2s. c o m } ProgressHandleMonitor pm = ProgressHandleMonitor.create("Computing plot"); Runnable operation = () -> { pm.beginTask("Computing plot...", 100); try { checkBandsForRange(); setRange(X_VAR, rasterX, dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null, SubProgressMonitor.create(pm, 15)); setRange(Y_VAR, rasterY, dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null, SubProgressMonitor.create(pm, 15)); BufferedImage densityPlotImage = ProductUtils.createDensityPlotImage(rasterX, axisRangeControls[X_VAR].getMin().floatValue(), axisRangeControls[X_VAR].getMax().floatValue(), rasterY, axisRangeControls[Y_VAR].getMin().floatValue(), axisRangeControls[Y_VAR].getMax().floatValue(), dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null, 512, 512, backgroundColor, null, SubProgressMonitor.create(pm, 70)); densityPlotImage = new BufferedImage(untoggledColorModel, densityPlotImage.getRaster(), densityPlotImage.isAlphaPremultiplied(), null); plotColorsInverted = false; checkBandsForRange(); double minX = axisRangeControls[X_VAR].getMin(); double maxX = axisRangeControls[X_VAR].getMax(); double minY = axisRangeControls[Y_VAR].getMin(); double maxY = axisRangeControls[Y_VAR].getMax(); if (minX > maxX || minY > maxY) { JOptionPane.showMessageDialog(chartPanel, "Failed to compute plot.\n" + "No Pixels considered..", CHART_TITLE, JOptionPane.ERROR_MESSAGE); plot.setDataset(null); return; } if (MathUtils.equalValues(minX, maxX, 1.0e-4)) { minX = Math.floor(minX); maxX = Math.ceil(maxX); } if (MathUtils.equalValues(minY, maxY, 1.0e-4)) { minY = Math.floor(minY); maxY = Math.ceil(maxY); } plot.setImage(densityPlotImage); plot.setImageDataBounds(new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY)); axisRangeControls[X_VAR].adjustComponents(minX, maxX, NUM_DECIMALS); axisRangeControls[Y_VAR].adjustComponents(minY, maxY, NUM_DECIMALS); // plot.getDomainAxis().setLabel(StatisticChartStyling.getAxisLabel(getRaster(X_VAR), "Entropy", false)); // plot.getRangeAxis().setLabel(StatisticChartStyling.getAxisLabel(getRaster(Y_VAR), "Alpha", false)); plot.getDomainAxis().setLabel("Entropy"); plot.getRangeAxis().setLabel("Alpha"); toggleZoneOverlayCheckBox.setEnabled(true); // clear the list java.util.List<XYAnnotation> annotList = plot.getAnnotations(); for (XYAnnotation an : annotList) { plot.removeAnnotation(an); } if (toggleZoneOverlayCheckBox.isSelected()) { drawZoneOverlay(); } } catch (Exception e) { SnapApp.getDefault().handleError("Failed to compute plot", e); } finally { pm.done(); } }; ProgressUtils.runOffEventThreadWithProgressDialog(operation, "Computing plot", pm.getProgressHandle(), true, 50, 1000); }
From source file:org.geoserver.wms.map.RenderedImageMapOutputFormatTest.java
@Test public void testGetMapOnByteNodataGrayScale() throws Exception { GetMapRequest request = new GetMapRequest(); CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84; ReferencedEnvelope bbox = new ReferencedEnvelope(new Envelope(145, 146, -43, -41), crs); request.setBbox(bbox);/*from ww w . j av a 2 s.c o m*/ request.setHeight(768); request.setWidth(384); request.setSRS("urn:x-ogc:def:crs:EPSG:4326"); request.setFormat("image/png"); request.setTransparent(true); final WMSMapContent map = new WMSMapContent(request); map.setMapHeight(768); map.setMapWidth(384); map.setBgColor(BG_COLOR); map.setTransparent(true); map.getViewport().setBounds(bbox); addRasterToMap(map, TAZ_BYTE); map.getViewport().setBounds(bbox); RenderedImageMap imageMap = this.rasterMapProducer.produceMap(map); RenderedOp op = (RenderedOp) imageMap.getImage(); BufferedImage image = op.getAsBufferedImage(); imageMap.dispose(); // check that a pixel in nodata area is transparent assertEquals(0, image.getRaster().getSample(40, 400, 0)); assertEquals(0, image.getRaster().getSample(40, 400, 1)); }
From source file:org.apache.cocoon.reading.ImageReader.java
protected void processStream(InputStream inputStream) throws IOException, ProcessingException { if (hasTransform()) { if (getLogger().isDebugEnabled()) { getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x" + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires); }/*from ww w . j a v a 2 s. c o m*/ /* * NOTE (SM): * Due to Bug Id 4502892 (which is found in *all* JVM implementations from * 1.2.x and 1.3.x on all OS!), we must buffer the JPEG generation to avoid * that connection resetting by the peer (user pressing the stop button, * for example) crashes the entire JVM (yes, dude, the bug is *that* nasty * since it happens in JPEG routines which are native!) * I'm perfectly aware of the huge memory problems that this causes (almost * doubling memory consuption for each image and making the GC work twice * as hard) but it's *far* better than restarting the JVM every 2 minutes * (since this is the average experience for image-intensive web application * such as an image gallery). * Please, go to the <a href="http://developer.java.sun.com/developer/bugParade/bugs/4502892.html">Sun Developers Connection</a> * and vote this BUG as the one you would like fixed sooner rather than * later and all this hack will automagically go away. * Many deep thanks to Michael Hartle <mhartle@hartle-klug.com> for tracking * this down and suggesting the workaround. * * UPDATE (SM): * This appears to be fixed on JDK 1.4 */ try { byte content[] = readFully(inputStream); ImageIcon icon = new ImageIcon(content); BufferedImage original = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB); BufferedImage currentImage = original; currentImage.getGraphics().drawImage(icon.getImage(), 0, 0, null); if (width > 0 || height > 0) { double ow = icon.getImage().getWidth(null); double oh = icon.getImage().getHeight(null); if (usePercent) { if (width > 0) { width = Math.round((int) (ow * width) / 100); } if (height > 0) { height = Math.round((int) (oh * height) / 100); } } AffineTransformOp filter = new AffineTransformOp(getTransform(ow, oh, width, height), AffineTransformOp.TYPE_BILINEAR); WritableRaster scaledRaster = filter.createCompatibleDestRaster(currentImage.getRaster()); filter.filter(currentImage.getRaster(), scaledRaster); currentImage = new BufferedImage(original.getColorModel(), scaledRaster, true, null); } if (null != grayscaleFilter) { grayscaleFilter.filter(currentImage, currentImage); } if (null != colorFilter) { colorFilter.filter(currentImage, currentImage); } // JVM Bug handling if (JVMBugFixed) { JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage); p.setQuality(this.quality[0], true); encoder.setJPEGEncodeParam(p); encoder.encode(currentImage); } else { ByteArrayOutputStream bstream = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bstream); JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage); p.setQuality(this.quality[0], true); encoder.setJPEGEncodeParam(p); encoder.encode(currentImage); out.write(bstream.toByteArray()); } out.flush(); } catch (ImageFormatException e) { throw new ProcessingException( "Error reading the image. " + "Note that only JPEG images are currently supported."); } finally { // Bugzilla Bug 25069, close inputStream in finally block // this will close inputStream even if processStream throws // an exception inputStream.close(); } } else { // only read the resource - no modifications requested if (getLogger().isDebugEnabled()) { getLogger().debug("passing original resource"); } super.processStream(inputStream); } }
From source file:org.sejda.sambox.pdmodel.graphics.image.PDImageXObject.java
private BufferedImage applyMask(BufferedImage image, BufferedImage mask, boolean isSoft) { if (mask == null) { return image; }//from ww w . java 2 s . c o m int width = image.getWidth(); int height = image.getHeight(); // scale mask to fit image, or image to fit mask, whichever is larger if (mask.getWidth() < width || mask.getHeight() < height) { mask = scaleImage(mask, width, height); } else if (mask.getWidth() > width || mask.getHeight() > height) { width = mask.getWidth(); height = mask.getHeight(); image = scaleImage(image, width, height); } // compose to ARGB BufferedImage masked = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); WritableRaster src = image.getRaster(); WritableRaster dest = masked.getRaster(); WritableRaster alpha = mask.getRaster(); float[] rgb = new float[4]; float[] rgba = new float[4]; float[] alphaPixel = null; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { src.getPixel(x, y, rgb); rgba[0] = rgb[0]; rgba[1] = rgb[1]; rgba[2] = rgb[2]; alphaPixel = alpha.getPixel(x, y, alphaPixel); if (isSoft) { rgba[3] = alphaPixel[0]; } else { rgba[3] = 255 - alphaPixel[0]; } dest.setPixel(x, y, rgba); } } return masked; }
From source file:org.geowebcache.filter.request.RasterFilter.java
private boolean lookupSubsample(GridSubset grid, long[] idx, int zoomDiff) { BufferedImage mat = matrices.get(grid.getName())[(int) idx[2]]; int sampleChange = 1 << (-1 * zoomDiff); long[] gridCoverage = grid.getCoverage((int) idx[2]); // Changing index to top left hand origin int baseX = (int) (idx[0] - gridCoverage[0]); int baseY = (int) (gridCoverage[3] - idx[1]); int width = mat.getWidth(); int height = mat.getHeight(); int startX = Math.max(0, baseX); int stopX = Math.min(width, baseX + sampleChange); int startY = Math.min(baseY, height - 1); int stopY = Math.max(0, baseY - sampleChange); int x = -1;//from w w w . j a v a2 s. c o m int y = -1; // Lock, in case someone wants to replace the matrix synchronized (mat) { try { // Try center and edges first x = (stopX + startX) / 2; y = (startY + stopY) / 2; if (mat.getRaster().getSample(x, y, 0) == 0 || mat.getRaster().getSample(stopX - 1, stopY + 1, 0) == 0 || mat.getRaster().getSample(stopX - 1, startY, 0) == 0 || mat.getRaster().getSample(startX, stopY + 1, 0) == 0) { return true; } // Do the hard work, loop over all pixels x = startX; y = startY; // Left to right while (x < stopX) { // Bottom to top while (y > stopY) { if (mat.getRaster().getSample(x, y, 0) == 0) { return true; } y--; } x++; y = startY; } } catch (ArrayIndexOutOfBoundsException aioob) { log.error("x:" + x + " y:" + y + " (" + mat.getWidth() + " " + mat.getHeight() + ")"); } } return false; }
From source file:com.neophob.sematrix.generator.Textwriter.java
/** * create image./* w ww .j a v a2 s .c om*/ * * @param text the text */ public void createTextImage(String text) { //only load if needed if (StringUtils.equals(text, this.text)) { return; } this.text = text; BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = img.createGraphics(); FontRenderContext frc = g2.getFontRenderContext(); TextLayout layout = new TextLayout(text, font, frc); Rectangle2D rect = layout.getBounds(); int h = (int) (0.5f + rect.getHeight()); maxXPos = (int) (0.5f + rect.getWidth()) + 5; ypos = internalBufferYSize - (internalBufferYSize - h) / 2; img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_INT_RGB); g2 = img.createGraphics(); g2.setColor(color); g2.setFont(font); g2.setClip(0, 0, maxXPos, internalBufferYSize); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString(text, xpos, ypos); DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer(); textBuffer = dbi.getData(); g2.dispose(); wait = 0; xofs = 0; scrollRight = false; }