List of usage examples for java.awt.image BufferedImage getColorModel
public ColorModel getColorModel()
From source file:org.deegree.services.wps.provider.jrxml.contentprovider.map.MapContentProvider.java
private File writeImage(BufferedImage bi) throws ProcessletException { FileOutputStream fos = null;/*w w w . j a v a 2 s.c o m*/ try { File f = File.createTempFile("image", ".png"); fos = new FileOutputStream(f); PNGEncodeParam encodeParam = PNGEncodeParam.getDefaultEncodeParam(bi); if (encodeParam instanceof PNGEncodeParam.Palette) { PNGEncodeParam.Palette p = (PNGEncodeParam.Palette) encodeParam; byte[] b = new byte[] { -127 }; p.setPaletteTransparency(b); } com.sun.media.jai.codec.ImageEncoder encoder = ImageCodec.createImageEncoder("PNG", fos, encodeParam); encoder.encode(bi.getData(), bi.getColorModel()); LOG.debug("Wrote image to file: {}", f.toString()); return f; } catch (IOException e) { String msg = "Could not write image to file: " + e.getMessage(); LOG.debug(msg, e); throw new ProcessletException(msg); } finally { IOUtils.closeQuietly(fos); } }
From source file:nl.b3p.viewer.image.ImageTool.java
/** Reads an image from an http input stream. * * @param method Apache HttpClient GetMethod object * @param mime String representing the mime type of the image. * * @return BufferedImage//from www .ja v a 2 s . c om * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(HttpMethod method, String mime) throws Exception { ImageReader ir = null; BufferedImage i = null; try { if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de * HttpClient vernieuwing in kaartenbalie ? */ if (mimeType == null) { mimeType = "image/png"; } if (mimeType == null) { log.error("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); throw new Exception("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); } ir = getReader(mimeType); if (ir == null) { log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); throw new Exception("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); } //TODO Make smarter.. Possibly faster... But keep reporting! InputStream is = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[2048]; while (bytesRead != -1) { bytesRead = is.read(buffer, 0, buffer.length); if (bytesRead > 0) { baos.write(buffer, 0, bytesRead); } } ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); i = ir.read(0); //if image is a png, has no alpha and has a tRNS then make that color transparent. if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) { PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0); if (metadata.tRNS_present) { int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue); BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < i.getWidth(); x++) { for (int y = 0; y < i.getHeight(); y++) { int rgb = i.getRGB(x, y); rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb; tmp.setRGB(x, y, rgb); } } i = tmp; } } } finally { if (ir != null) { ir.dispose(); } } return i; }
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); }//w ww . jav a 2s. c om /* * 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.yccheok.jstock.gui.Utils.java
private static boolean hasAlpha(Image image) { // If buffered image, the color model is readily available if (image instanceof BufferedImage) { BufferedImage bimage = (BufferedImage) image; return bimage.getColorModel().hasAlpha(); }// www. j ava2s . c o m // Use a pixel grabber to retrieve the image's color model; // grabbing a single pixel is usually sufficient PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false); try { pg.grabPixels(); } catch (InterruptedException e) { } // Get the image's color model ColorModel cm = pg.getColorModel(); return cm.hasAlpha(); }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java
/** * @see Graphics2D#drawImage(BufferedImage, BufferedImageOp, int, int) *///from w w w . j a v a 2s. c o m @Override public void drawImage(final BufferedImage img, final BufferedImageOp op, final int x, final int y) { BufferedImage result = img; if (op != null) { result = op.createCompatibleDestImage(img, img.getColorModel()); result = op.filter(img, result); } drawImage(result, x, y, null); }
From source file:org.apache.cocoon.reading.RepoImageReader.java
/** * @return the time the read source was last modified or 0 if it is not * possible to detect/*from w ww . ja v a2 s. c o m*/ */ /* public long getLastModified() { if (hasRanges()) { // This is a byte range request so we can't use the cache, return null. return 0; } if (quickTest) { return inputSource.getLastModified(); } final String systemId = (String) documents.get(request.getRequestURI()); // Note: getURI() might be null in some incomplete implementations final String sourceURI = inputSource.getURI(); if (systemId == null || (sourceURI != null && sourceURI.equals(systemId))) { return inputSource.getLastModified(); } documents.remove(request.getRequestURI()); return 0; }*/ protected void processStream(InputStream inputStream) throws IOException, ProcessingException { if (inputStream != null) { if (hasTransform()) { if (getLogger().isDebugEnabled()) { getLogger().debug("image " + ((width == 0) ? "?" : Integer.toString(width)) + "x" + ((height == 0) ? "?" : Integer.toString(height)) + " expires: " + expires); } 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); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam p = encoder.getDefaultJPEGEncodeParam(currentImage); p.setQuality(this.quality[0], true); encoder.setJPEGEncodeParam(p); encoder.encode(currentImage); 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 { try { InputStream is = inputStream; long expires = parameters.getParameterAsInteger("expires", -1); if (expires > 0) { response.setDateHeader("Expires", System.currentTimeMillis() + expires); } response.setHeader("Accept-Ranges", "bytes"); byte[] buffer = new byte[8192]; int length; while ((length = is.read(buffer)) > -1) { out.write(buffer, 0, length); } is.close(); out.flush(); } catch (RuntimeException e) { throw e; } finally { // Bugzilla Bug 25069, close inputStream in finally block // this will close inputStream even if processStream throws // an exception inputStream.close(); } } } else { throw new IOException("Deals: Problem, resource not found or Repository not working correctly"); } }
From source file:ded.ui.DiagramController.java
/** Get and log some details related to display scaling, particularly * to help diagnose the graphics bugs on HiDPI/Retina displays. */ public void logDisplayScaling() { // Based on code from // http://lubosplavucha.com/java/2013/09/02/retina-support-in-java-for-awt-swing/ try {/* w w w . j a v a 2 s .c om*/ // Dump a bunch of possibly interesting JVM properties. String propertyNames[] = { "awt.toolkit", "java.awt.graphicsenv", "java.runtime.name", "java.runtime.version", "java.vendor", "java.version", "java.vm.name", "java.vm.vendor", "java.vm.version", }; for (String name : propertyNames) { this.log("property " + name + ": " + System.getProperty(name)); } // Try a property specific to the Apple JVM. this.log("apple.awt.contentScaleFactor: " + Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor")); // Try something specific to OpenJDK. Here, we // reflectively query some private field. Yuck. GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); try { Field field = gd.getClass().getDeclaredField("scale"); field.setAccessible(true); this.log("GraphicsEnvironment.scale: " + field.get(gd)); } catch (NoSuchFieldException e) { this.log("GraphicsEnvironment does not have a 'scale' field"); } // Check some details of "compatible" images. GraphicsConfiguration gc = gd.getDefaultConfiguration(); BufferedImage bi = gc.createCompatibleImage(64, 64); ColorModel cm = bi.getColorModel(); this.log("compatible image color model: " + cm); // Do the same for a specific imageType that seems to be // commonly used, and that I am using when saving to PNG. bi = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); cm = bi.getColorModel(); this.log("TYPE_INT_ARGB color model: " + cm); // And one more. bi = new BufferedImage(64, 64, BufferedImage.TYPE_INT_RGB); cm = bi.getColorModel(); this.log("TYPE_INT_RGB color model: " + cm); } catch (Exception e) { this.log("exception during logDisplayScaling(): " + Util.getExceptionMessage(e)); this.logNoNewline(Util.getExceptionStackTrace(e)); } }
From source file:ded.ui.DiagramController.java
/** Check to see if the font is rendering properly. I have had a * lot of trouble getting this to work on a wide range of * machines and JVMs. If the font rendering does not work, just * alert the user to the problem but keep going. */ public void checkFontRendering() { // Render the glyph for 'A' in a box just large enough to // contain it when rendered properly. int width = 9; int height = 11; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); ColorModel colorModel = bi.getColorModel(); g.setColor(Color.WHITE);/* w w w . j a v a 2 s. c o m*/ g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); g.setFont(this.dedWindow.diagramFont); g.drawString("A", 0, 10); // Print that glyph as a string. StringBuilder sb = new StringBuilder(); for (int y = 0; y < height; y++) { int bits = 0; for (int x = 0; x < width; x++) { int pixel = bi.getRGB(x, y); int red = colorModel.getRed(pixel); int green = colorModel.getGreen(pixel); int blue = colorModel.getBlue(pixel); int alpha = colorModel.getAlpha(pixel); boolean isWhite = (red == 255 && green == 255 && blue == 255 && alpha == 255); boolean isBlack = (red == 0 && green == 0 && blue == 0 && alpha == 255); sb.append( isWhite ? "_" : isBlack ? "X" : ("(" + red + "," + green + "," + blue + "," + alpha + ")")); bits <<= 1; if (!isWhite) { bits |= 1; } } sb.append(String.format(" (0x%03X)\n", bits)); } // Also include some of the font metrics. FontMetrics fm = g.getFontMetrics(); sb.append("fm: ascent=" + fm.getAscent() + " leading=" + fm.getLeading() + " charWidth('A')=" + fm.charWidth('A') + " descent=" + fm.getDescent() + " height=" + fm.getHeight() + "\n"); String actualGlyph = sb.toString(); g.dispose(); // The expected glyph and metrics. String expectedGlyph = "_________ (0x000)\n" + "____X____ (0x010)\n" + "___X_X___ (0x028)\n" + "___X_X___ (0x028)\n" + "__X___X__ (0x044)\n" + "__X___X__ (0x044)\n" + "__XXXXX__ (0x07C)\n" + "_X_____X_ (0x082)\n" + "_X_____X_ (0x082)\n" + "_X_____X_ (0x082)\n" + "_________ (0x000)\n" + "fm: ascent=10 leading=1 charWidth('A')=9 descent=3 height=14\n"; if (!expectedGlyph.equals(actualGlyph)) { // Currently, this is known to happen when using OpenJDK 6 // and 7, with 6 being close to right and 7 being very bad. // I also have reports of it happening on certain Mac OS/X // systems, but I haven't been able to determine what the // important factor there is. String warningMessage = "There is a problem with the font rendering. The glyph " + "for the letter 'A' should look like:\n" + expectedGlyph + "but it renders as:\n" + actualGlyph + "\n" + "This probably means there is a bug in the TrueType " + "font library. You might try a different Java version. " + "(I'm working on how to solve this permanently.)"; System.err.println(warningMessage); this.log(warningMessage); SwingUtil.errorMessageBox(null /*component*/, warningMessage); } }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox.PDFAsVisualSignatureBuilder.java
private void readTableResources(PDFBoxTable table, PDDocument template) throws PdfAsException, IOException { float[] colsSizes = table.getColsRelativeWith(); int max_cols = table.getColCount(); float padding = table.getPadding(); if (colsSizes == null) { colsSizes = new float[max_cols]; // set the column ratio for all columns to 1 for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { colsSizes[cols_idx] = 1;//from w w w. j ava 2 s . com } } logger.debug("TOTAL Width: " + table.getWidth()); float total = 0; for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { total += colsSizes[cols_idx]; } for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { colsSizes[cols_idx] = (colsSizes[cols_idx] / total) * table.getWidth(); } for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { logger.debug("Col: " + cols_idx + " : " + colsSizes[cols_idx]); } /* * if(!addedFonts.contains(table.getFont().getFont(null))) { PDFont font * = table.getFont().getFont(template); addedFonts.add(font); * innerFormResources.addFont(font); } * * if(!addedFonts.contains(table.getValueFont().getFont(null))) { PDFont * font = table.getValueFont().getFont(template); addedFonts.add(font); * innerFormResources.addFont(font); } */ for (int i = 0; i < table.getRowCount(); i++) { ArrayList<Entry> row = table.getRow(i); for (int j = 0; j < row.size(); j++) { Entry cell = (Entry) row.get(j); if (cell.getType() == Entry.TYPE_IMAGE) { String img_value = (String) cell.getValue(); String img_ref = createHashedId(img_value); if (!images.containsKey(img_ref)) { BufferedImage img = ImageUtils.getImage(img_value, settings); float width = colsSizes[j]; float height = table.getRowHeights()[i] + padding * 2; float iwidth = (int) Math.floor((double) width); iwidth -= 2 * padding; float iheight = (int) Math.floor((double) height); iheight -= 2 * padding; float origWidth = (float) img.getWidth(); float origHeight = (float) img.getHeight(); if (table.style != null) { if (table.style.getImageScaleToFit() != null) { iwidth = table.style.getImageScaleToFit().getWidth(); iheight = table.style.getImageScaleToFit().getHeight(); } } float wfactor = iwidth / origWidth; float hfactor = iheight / origHeight; float scaleFactor = wfactor; if (hfactor < wfactor) { scaleFactor = hfactor; } iwidth = (float) Math.floor((double) (scaleFactor * origWidth)); iheight = (float) Math.floor((double) (scaleFactor * origHeight)); logger.debug("Scaling image to: " + iwidth + " x " + iheight); if (this.designer.properties.getSignatureProfileSettings().isPDFA()) { img = ImageUtils.removeAlphaChannel(img); } else { if (img.getAlphaRaster() == null && img.getColorModel().hasAlpha()) { img = ImageUtils.removeAlphaChannel(img); } } // img = ImageUtils.convertRGBAToIndexed(img); PDXObjectImage pdImage = new PDPixelMap(template, img); ImageObject image = new ImageObject(pdImage, iwidth, iheight); images.put(img_ref, image); innerFormResources.addXObject(pdImage, "Im"); } } else if (cell.getType() == Entry.TYPE_TABLE) { PDFBoxTable tbl_value = (PDFBoxTable) cell.getValue(); readTableResources(tbl_value, template); } } } }
From source file:at.gv.egiz.pdfas.lib.impl.stamping.pdfbox2.PDFAsVisualSignatureBuilder.java
private void readTableResources(PDFBoxTable table, PDDocument template) throws PdfAsException, IOException { float[] colsSizes = table.getColsRelativeWith(); int max_cols = table.getColCount(); float padding = table.getPadding(); if (colsSizes == null) { colsSizes = new float[max_cols]; // set the column ratio for all columns to 1 for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { colsSizes[cols_idx] = 1;/*from w w w . j a va 2 s . c o m*/ } } logger.debug("TOTAL Width: " + table.getWidth()); float total = 0; for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { total += colsSizes[cols_idx]; } for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { colsSizes[cols_idx] = (colsSizes[cols_idx] / total) * table.getWidth(); } for (int cols_idx = 0; cols_idx < colsSizes.length; cols_idx++) { logger.debug("Col: " + cols_idx + " : " + colsSizes[cols_idx]); } /* * if(!addedFonts.contains(table.getFont().getFont(null))) { PDFont font * = table.getFont().getFont(template); addedFonts.add(font); * innerFormResources.addFont(font); } * * if(!addedFonts.contains(table.getValueFont().getFont(null))) { PDFont * font = table.getValueFont().getFont(template); addedFonts.add(font); * innerFormResources.addFont(font); } */ for (int i = 0; i < table.getRowCount(); i++) { ArrayList<Entry> row = table.getRow(i); for (int j = 0; j < row.size(); j++) { Entry cell = (Entry) row.get(j); if (cell.getType() == Entry.TYPE_IMAGE) { String img_value = (String) cell.getValue(); String img_ref = createHashedId(img_value); if (!images.containsKey(img_ref)) { BufferedImage img = ImageUtils.getImage(img_value, settings); float width = colsSizes[j]; float height = table.getRowHeights()[i] + padding * 2; float iwidth = (int) Math.floor((double) width); iwidth -= 2 * padding; float iheight = (int) Math.floor((double) height); iheight -= 2 * padding; float origWidth = (float) img.getWidth(); float origHeight = (float) img.getHeight(); if (table.style != null) { if (table.style.getImageScaleToFit() != null) { iwidth = table.style.getImageScaleToFit().getWidth(); iheight = table.style.getImageScaleToFit().getHeight(); } } float wfactor = iwidth / origWidth; float hfactor = iheight / origHeight; float scaleFactor = wfactor; if (hfactor < wfactor) { scaleFactor = hfactor; } iwidth = (float) Math.floor((double) (scaleFactor * origWidth)); iheight = (float) Math.floor((double) (scaleFactor * origHeight)); logger.debug("Scaling image to: " + iwidth + " x " + iheight); if (this.designer.properties.getSignatureProfileSettings().isPDFA()) { img = ImageUtils.removeAlphaChannel(img); } else { if (img.getAlphaRaster() == null && img.getColorModel().hasAlpha()) { img = ImageUtils.removeAlphaChannel(img); } } // img = ImageUtils.convertRGBAToIndexed(img); PDImageXObject pdImage = LosslessFactory.createFromImage(template, img); ImageObject image = new ImageObject(pdImage, iwidth, iheight); images.put(img_ref, image); innerFormResources.add(pdImage, "Im"); } } else if (cell.getType() == Entry.TYPE_TABLE) { PDFBoxTable tbl_value = (PDFBoxTable) cell.getValue(); readTableResources(tbl_value, template); } } } }