@Override public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = this.getSize(); int width = (int) d.getWidth(); int height = (int) d.getHeight(); g2.clearRect(0, 0, width, height); AffineTransform at = null; if (cachedImage == null) { renderOffscreen(); } if (getOrientation() == SwingConstants.VERTICAL) { at = AffineTransform.getScaleInstance((double) width / 10f, (double) height / DEFAULT_HEIGHT); } if (getOrientation() == SwingConstants.HORIZONTAL) { at = AffineTransform.getScaleInstance( (double) width / DEFAULT_WIDTH, (double) height / (double) 10); } drawBackground(g2); g2.drawRenderedImage(cachedImage, at); }
/** * Render the raster on the java.awt.Graphics * * @param graphics java.awt.Graphics to draw the image on. */ public void render(Graphics graphics) { if (getNeedToRegenerate() || getNeedToReposition() || !isVisible()) { if (DEBUG) { logger.fine("OMRasterObject.render(): need to regenerate or not visible!"); } return; } // copy the graphic, so our transform doesn't cascade to // others... Graphics g = graphics.create(); // Just a little check to find out if someone is rushing // things. If a Image isn't fully loaded, the getWidth will // return -1. This is just a courtesy notification in case // someone isn't seeing their image, and don't know why. if (colorModel == COLORMODEL_IMAGEICON && (getWidth() == -1)) { logger.fine( "OMRasterObject.render: Attempting to draw a Image that is not ready! Image probably wasn't available."); } if (g instanceof Graphics2D && rotationAngle != DEFAULT_ROTATIONANGLE) { // rotate about our image center point rotate((Graphics2D) g); } if (bitmap != null) { if (DEBUG) { logger.fine( "OMRasterObject.render() | drawing " + width + "x" + height + " image at " + point1.x + ", " + point1.y); } if (g instanceof Graphics2D && bitmap instanceof RenderedImage) { // Affine translation for placement... ((Graphics2D) g) .drawRenderedImage( (RenderedImage) bitmap, new AffineTransform(1f, 0f, 0f, 1f, point1.x, point1.y)); // Undo the affine translation for future graphics?? Apparently // not... // ((Graphics2D) g).translate(-point1.x, -point1.y); } else { g.drawImage(bitmap, point1.x, point1.y, this); } } else { if (DEBUG) logger.fine("OMRasterObject.render: ignoring null bitmap"); } if (isSelected() || logger.isLoggable(Level.FINER)) { super.render(g); } renderLabel(graphics); }
private <T> T scaleImageUsingAffineTransformation(final BufferedImage bufferedImage, T target) { BufferedImage destinationImage = generateDestinationImage(); Graphics2D graphics2D = destinationImage.createGraphics(); AffineTransform transformation = AffineTransform.getScaleInstance( ((double) getQualifiedWidth() / bufferedImage.getWidth()), ((double) getQualifiedHeight() / bufferedImage.getHeight())); graphics2D.drawRenderedImage(bufferedImage, transformation); graphics2D.addRenderingHints(retrieveRenderingHints()); try { if (target instanceof File) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "File")); ImageIO.write(destinationImage, imageType.toString(), (File) target); } else if (target instanceof ImageOutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "ImageOutputStream")); ImageIO.write(destinationImage, imageType.toString(), (ImageOutputStream) target); } else if (target instanceof OutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "OutputStream")); ImageIO.write(destinationImage, imageType.toString(), (OutputStream) target); } else { target = null; } } catch (IOException e) { e.printStackTrace(); } return target; }
/** * Renders an image on the device * * @param graphics the image location on the screen, x coordinate * @param x the image location on the screen, y coordinate * @param y the image * @param image DOCUMENT ME! * @param rotation the image rotatation * @param opacity DOCUMENT ME! */ private void renderImage( Graphics2D graphics, double x, double y, BufferedImage image, double rotation, float opacity) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("drawing Image @" + x + "," + y); } AffineTransform markAT = new AffineTransform(); markAT.translate(x, y); markAT.rotate(rotation); markAT.translate(-image.getWidth() / 2.0, -image.getHeight() / 2.0); graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); Object interpolation = graphics.getRenderingHint(RenderingHints.KEY_INTERPOLATION); if (interpolation == null) { interpolation = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR; } try { graphics.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.drawRenderedImage(image, markAT); } finally { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation); } }
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); if (floorPlan != null) { // colocando a posicao inicial na tela e pegando uma instancia do transformador AffineTransform at = AffineTransform.getTranslateInstance(transfPosX, transfPosY); // double escala = INDICE_ESCALA / 100.0; // double sx = ((double) floorPlan.getWidth()) * escala ; // double sy = ((double) floorPlan.getHeight()) * escala; at.scale(escala, escala); System.out.println("Meu teste: " + floorPlan.getWidth() + " " + floorPlan.getHeight()); g2d.drawRenderedImage(floorPlan, at); } if (pathNormalizer != null) { g2d.setColor(Color.red); g2d.draw(pathNormalizer); } if (path != null) { g2d.setColor(Color.black); g2d.draw(path); } }
/** This template method should set the xlink:href attribute on the input Element parameter */ protected void handleHREF( RenderedImage image, Element imageElement, SVGGeneratorContext generatorContext) throws SVGGraphics2DIOException { // // Create an buffered image if necessary // BufferedImage buf = null; if (image instanceof BufferedImage && ((BufferedImage) image).getType() == getBufferedImageType()) { buf = (BufferedImage) image; } else { Dimension size = new Dimension(image.getWidth(), image.getHeight()); buf = buildBufferedImage(size); Graphics2D g = createGraphics(buf); g.drawRenderedImage(image, IDENTITY); g.dispose(); } // // Cache image and set xlink:href // cacheBufferedImage(imageElement, buf, generatorContext); }
@Override protected void paintComponent(Graphics graphics) { // Fill in the background: Graphics2D g = (Graphics2D) graphics; Shape clip = g.getClip(); g.setColor(LightZoneSkin.Colors.NeutralGray); g.fill(clip); if (preview == null) { PlanarImage image = currentImage.get(); if (image == null) { engine.update(null, false); } else if (visibleRect != null && getHeight() > 1 && getWidth() > 1) { preview = cropScaleGrayscale(visibleRect, image); } } if (preview != null) { int dx, dy; AffineTransform transform = new AffineTransform(); if (getSize().width > preview.getWidth()) dx = (getSize().width - preview.getWidth()) / 2; else dx = 0; if (getSize().height > preview.getHeight()) dy = (getSize().height - preview.getHeight()) / 2; else dy = 0; transform.setToTranslation(dx, dy); try { g.drawRenderedImage(preview, transform); } catch (Exception e) { e.printStackTrace(); } } }
public static void scalePictureToMax( InputStream in, OutputStream out, int maxWidth, int maxHeight) throws Exception { BufferedImage bsrc = ImageIO.read(in); int height = 0; int width = 0; double aspectRatio = ((double) bsrc.getHeight()) / ((double) bsrc.getWidth()); double maxAR = ((double) maxHeight) / ((double) maxWidth); if (aspectRatio > maxAR) { height = maxHeight; width = (int) Math.round(maxHeight / aspectRatio); } else { width = maxWidth; height = (int) Math.round(maxWidth * aspectRatio); } BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bdest.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance( (double) width / bsrc.getWidth(), (double) height / bsrc.getHeight()); g.drawRenderedImage(bsrc, at); ImageIO.write(bdest, "PNG", out); }
@Override public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); if (dst == null) { if (addMargins) { ColorModel cm = src.getColorModel(); dst = new BufferedImage( cm, cm.createCompatibleWritableRaster(src.getWidth(), src.getHeight()), cm.isAlphaPremultiplied(), null); } else dst = createCompatibleDestImage(src, null); } // Make a black mask from the image's alpha channel float[][] extractAlpha = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, opacity} }; BufferedImage shadow = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); new BandCombineOp(extractAlpha, null).filter(src.getRaster(), shadow.getRaster()); shadow = new GaussianFilter(radius).filter(shadow, null); Graphics2D g = dst.createGraphics(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); if (addMargins) { int radius2 = radius / 2; int topShadow = Math.max(0, radius - yOffset); int leftShadow = Math.max(0, radius - xOffset); g.translate(topShadow, leftShadow); } g.drawRenderedImage(shadow, AffineTransform.getTranslateInstance(xOffset, yOffset)); if (!shadowOnly) { g.setComposite(AlphaComposite.SrcOver); g.drawRenderedImage(src, null); } g.dispose(); return dst; }
/** * Crea la versión del usuario sobre el espacio de un objeto BufferedImage, para editar y guardar * bytes. * * @param image La imagen a poner dentro del espacio del usuario, quita las interferencias de * compresión. * @return La versión del usuario sobre el espacio de la imagen proporcionada. */ public BufferedImage userSpace(BufferedImage image) { // Crea newImg con los atributos de la imagen BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR); Graphics2D graphics = newImg.createGraphics(); graphics.drawRenderedImage(image, null); graphics.dispose(); // Libera toda la memoria asignada para esta imagen return newImg; }
public BufferedImage filter(BufferedImage src, BufferedImage dst) { if (dst == null) dst = createCompatibleDestImage(src, null); BufferedImage tsrc = src; float cx = (float) src.getWidth() * centreX; float cy = (float) src.getHeight() * centreY; float imageRadius = (float) Math.sqrt(cx * cx + cy * cy); float translateX = (float) (distance * Math.cos(angle)); float translateY = (float) (distance * -Math.sin(angle)); float scale = zoom; float rotate = rotation; float maxDistance = distance + Math.abs(rotation * imageRadius) + zoom * imageRadius; int steps = log2((int) maxDistance); translateX /= maxDistance; translateY /= maxDistance; scale /= maxDistance; rotate /= maxDistance; if (steps == 0) { Graphics2D g = dst.createGraphics(); g.drawRenderedImage(src, null); g.dispose(); return dst; } BufferedImage tmp = createCompatibleDestImage(src, null); for (int i = 0; i < steps; i++) { Graphics2D g = tmp.createGraphics(); g.drawImage(tsrc, null, null); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); g.translate(cx + translateX, cy + translateY); g.scale( 1.0001 + scale, 1.0001 + scale); // The .0001 works round a bug on Windows where drawImage throws an // ArrayIndexOutofBoundException if (rotation != 0) g.rotate(rotate); g.translate(-cx, -cy); g.drawImage(dst, null, null); g.dispose(); BufferedImage ti = dst; dst = tmp; tmp = ti; tsrc = dst; translateX *= 2; translateY *= 2; scale *= 2; rotate *= 2; } return dst; }
/** * Scale the given BufferedImage to the given width and height. Return the new scaled * BufferedImage. */ public static BufferedImage scale(BufferedImage bsrc, int width, int height) { AffineTransform at = AffineTransform.getScaleInstance( (double) width / bsrc.getWidth(), (double) height / bsrc.getHeight()); BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bdest.createGraphics(); g.drawRenderedImage(bsrc, at); return bdest; }
private static BufferedImage createCompatibleImage(BufferedImage image) { GraphicsConfiguration gc = BufferedImageGraphicsConfig.getConfig(image); int w = image.getWidth(); int h = image.getHeight(); BufferedImage result = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT); Graphics2D g2 = result.createGraphics(); g2.drawRenderedImage(image, null); g2.dispose(); return result; }
/** * Scales the image to the given size. The returned image has pixel type * BufferedImage.TYPE_INT_ARGB * * @param src source image * @param destWidth width to scale to * @param destHeight height to scale to * @return the scaled image */ public static BufferedImage scaleImage(BufferedImage src, int destWidth, int destHeight) { BufferedImage dest = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = dest.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance( (double) destWidth / src.getWidth(), (double) destHeight / src.getHeight()); g.drawRenderedImage(src, at); return dest; }
public static RenderedImage createRenderedImage(RenderedImage image, Color bkg) { if (bkg == null) return image; BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setBackground(bkg); g.clearRect(0, 0, image.getWidth(), image.getHeight()); g.drawRenderedImage(image, new AffineTransform()); return bufferedImage; }
public void drawRenderedImage(RenderedImage image, AffineTransform xform) { if (comp == null || comp instanceof AlphaComposite) super.drawRenderedImage(image, xform); else { createBuffer(); Graphics2D g2d = (Graphics2D) buffer.getGraphics(); g2d.setRenderingHints(this.getRenderingHints()); g2d.drawRenderedImage(image, xform); drawComposite(buffer.getRaster().getBounds(), null); } }
public BufferedImage convertImageType(BufferedImage sourceImage, int type) { BufferedImage targetImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), type); Graphics2D graphics = targetImage.createGraphics(); graphics.drawRenderedImage(sourceImage, null); graphics.dispose(); return targetImage; }
public static ImageIcon scale(ImageIcon img, int width, int height) throws IOException { BufferedImage bsrc = new BufferedImage(img.getIconWidth(), img.getIconHeight(), BufferedImage.TYPE_INT_ARGB); bsrc.getGraphics().drawImage(img.getImage(), 0, 0, img.getImageObserver()); BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bdest.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance( (double) width / bsrc.getWidth(), (double) height / bsrc.getHeight()); g.drawRenderedImage(bsrc, at); return new ImageIcon(bdest); }
/** * rotates an image * * @param image the image to rotate * @param angle the angle of rotation * @return the rotated image */ public static BufferedImage rotate(BufferedImage image, double angle) { GraphicsConfiguration gc = getDefaultConfiguration(); double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle)); int w = image.getWidth(), h = image.getHeight(); int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin); int transparency = image.getColorModel().getTransparency(); BufferedImage result = gc.createCompatibleImage(neww, newh, transparency); Graphics2D g = result.createGraphics(); g.translate((neww - w) / 2, (newh - h) / 2); g.rotate(angle, w / 2, h / 2); g.drawRenderedImage(image, null); return result; }
public void paint(Graphics g) { if (layer == null) { logger.warning("NULL layer, skipping..."); return; } OMGraphicList list = layer.getList(); Projection proj = layer.getProjection(); Graphics2D g2 = (Graphics2D) g; if (layer.isProjectionOK(proj)) { if (getBuffer() == null) { // Not sure how we get here, but it's here just in case so that // the list might get painted if it exists and the buffered // image wasn't created. logger.fine("creating image buffer in paint"); if (list != null) { setBuffer(createAndPaintImageBuffer(list)); } } BufferedImage bufferedImage = getBuffer(); setCompositeOnGraphics(g2); if (bufferedImage != null) { AffineTransform af = new AffineTransform(); af.translate(offset.getX(), offset.getY()); g2.drawRenderedImage((BufferedImage) bufferedImage, af); if (logger.isLoggable(Level.FINE)) { logger.fine("RenderingPolicy:" + layer.getName() + ": rendering buffer"); } } else if (list != null) { super.setRenderingHints(g); list.render(g); if (logger.isLoggable(Level.FINE)) { logger.fine(layer.getName() + ": rendering list directly"); } } } else if (logger.isLoggable(Level.FINE)) { logger.fine( layer.getName() + ".paint(): " + (list == null ? "NULL list, skipping..." : " skipping due to projection.")); } }
/** * Scale the given BufferedImage to width and height that are powers of two. Return the new scaled * BufferedImage. */ public static BufferedImage convertToPowerOf2(BufferedImage bsrc) { // find powers of 2 equal to or greater than current dimensions int newW = GLApp.getPowerOfTwoBiggerThan(bsrc.getWidth()); int newH = GLApp.getPowerOfTwoBiggerThan(bsrc.getHeight()); if (newW == bsrc.getWidth() && newH == bsrc.getHeight()) { return bsrc; // no change necessary } else { AffineTransform at = AffineTransform.getScaleInstance( (double) newW / bsrc.getWidth(), (double) newH / bsrc.getHeight()); BufferedImage bdest = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bdest.createGraphics(); g.drawRenderedImage(bsrc, at); return bdest; } }
/** * Renders an image on the device * * @param graphics the image location on the screen, x coordinate * @param x the image location on the screen, y coordinate * @param y the image * @param dx TODO * @param dy TODO * @param image image to draw * @param rotation the image rotation in radians * @param composite the alpha blending/composition operator */ private void renderImage( Graphics2D graphics, double x, double y, double dx, double dy, BufferedImage image, double rotation, Composite composite, boolean isLabelObstacle) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("drawing Image @" + x + "," + y); } AffineTransform markAT = new AffineTransform(); if (ROUND_ICON_COORDS && rotation == 0) { // this results in sharper images to be painted long tx = Math.round(x + dx); long ty = Math.round(y + dy); markAT.translate(tx, ty); } else { markAT.translate(x, y); markAT.rotate(rotation); markAT.translate(dx, dy); } if (isLabelObstacle) { int w = Math.max(image.getWidth() * 1, 1); int h = Math.max(image.getHeight() * 1, 1); labelCache.put(new Rectangle2D.Double(x + dx, y + dy, w, h)); } graphics.setComposite(composite); Object interpolation = graphics.getRenderingHint(RenderingHints.KEY_INTERPOLATION); if (interpolation == null) { interpolation = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR; } try { graphics.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.drawRenderedImage(image, markAT); } finally { graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation); } }
private byte[] getROIData(ROI roi, Rectangle rectIMG) { byte[] dataROI; PlanarImage roiIMG = roi.getAsImage(); Rectangle rectROI = roiIMG.getBounds(); // Forcing to component colormodel in order to avoid packed bits ImageWorker w = new ImageWorker(); w.setImage(roiIMG); w.forceComponentColorModel(); RenderedImage img = w.getRenderedImage(); // BufferedImage test = new BufferedImage(rectIMG.width, rectIMG.height, BufferedImage.TYPE_BYTE_GRAY); ImageLayout2 layout = new ImageLayout2(test); layout.setMinX(img.getMinX()); layout.setMinY(img.getMinY()); layout.setWidth(img.getWidth()); layout.setHeight(img.getHeight()); // Lookup byte[] lut = new byte[256]; lut[255] = 1; lut[1] = 1; LookupTableJAI table = new LookupTableJAI(lut); RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout); RenderedOp transformed = LookupDescriptor.create(img, table, hints); Graphics2D gc2d = null; // Translation parameters in order to position the ROI data correctly in the Raster Space int trX = -rectIMG.x + rectROI.x - rectIMG.x; int trY = -rectIMG.y + rectROI.y - rectIMG.y; try { gc2d = test.createGraphics(); gc2d.drawRenderedImage(transformed, AffineTransform.getTranslateInstance(trX, trY)); } finally { gc2d.dispose(); } Rectangle testRect = new Rectangle(rectIMG.width, rectIMG.height); DataBufferByte dbRoi = (DataBufferByte) test.getData(testRect).getDataBuffer(); dataROI = dbRoi.getData(); // BufferedImage is stored in memory so the planarImage chain before can be disposed ImageUtilities.disposePlanarImageChain(transformed); // Flush of the BufferedImage test.flush(); return dataROI; }
// TODO better use affine transform while drawing @Deprecated public static Image rotate(Image img, double angle) { double sin = Math.abs(Math.sin(Math.toRadians(angle))), cos = Math.abs(Math.cos(Math.toRadians(angle))); int w = img.getWidth(null), h = img.getHeight(null); int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h * cos + w * sin); BufferedImage bimg = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bimg.createGraphics(); g.translate((neww - w) / 2, (newh - h) / 2); g.rotate(Math.toRadians(angle), w / 2, h / 2); g.drawRenderedImage(toBufferedImage(img), null); g.dispose(); return bimg; }
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (!(g instanceof Graphics2D)) return; Graphics2D g2 = (Graphics2D) g; AffineTransform at = fromImageToOuterTransform(); g2.drawRenderedImage(mapImage, at); drawPlayerTokens(g2); if (highlightedArea != null) { drawHighlightedArea(highlightedArea, g2); } drawPlayerInfo(g2); }
public BufferedImage filter(BufferedImage src, BufferedImage dst) { int w = src.getWidth(); int h = src.getHeight(); if (dst == null) { ColorModel dstCM = src.getColorModel(); dst = new BufferedImage( dstCM, dstCM.createCompatibleWritableRaster(width, height), dstCM.isAlphaPremultiplied(), null); } Graphics2D g = dst.createGraphics(); g.drawRenderedImage(src, AffineTransform.getTranslateInstance(-x, -y)); g.dispose(); return dst; }
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (g instanceof Graphics2D) { Graphics2D gg = (Graphics2D) g; if (backgroundImage != null) { gg.drawRenderedImage(backgroundImage, this.getMmToPxTransform()); } gg.setColor(Color.red); for (Point2D.Double p : this.pointList) { Point2D.Double sp = new Point2D.Double(); AffineTransform trans = this.getMmToPxTransform(); trans.transform(p, sp); drawCross(gg, sp, SIZE); if (p == selectedPoint) { gg.drawOval((int) (sp.x - SIZE / 2), (int) (sp.y - SIZE / 2), (int) SIZE, (int) SIZE); } } } }
/** * Construct a JPEGmage. * * @param stream The JPEG InputStream. */ public JPEGImage(InputStream stream) { com.sun.image.codec.jpeg.JPEGImageDecoder decoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGDecoder(stream); try { // decodeAsBufferedImage performs default color conversions image = decoder.decodeAsBufferedImage(); } catch (ImageFormatException e) { throw new RuntimeException(JaiI18N.getString("JPEGImageDecoder1")); } catch (IOException e) { throw new RuntimeException(JaiI18N.getString("JPEGImageDecoder2")); } minX = 0; minY = 0; tileWidth = width = image.getWidth(); tileHeight = height = image.getHeight(); // Force image to have a ComponentSampleModel // since SinglePixelPackedSampleModels are not working if (!(image.getSampleModel() instanceof ComponentSampleModel)) { int type = -1; int numBands = image.getSampleModel().getNumBands(); if (numBands == 1) { type = BufferedImage.TYPE_BYTE_GRAY; } else if (numBands == 3) { type = BufferedImage.TYPE_3BYTE_BGR; } else if (numBands == 4) { type = BufferedImage.TYPE_4BYTE_ABGR; } else { throw new RuntimeException(JaiI18N.getString("JPEGImageDecoder3")); } BufferedImage bi = new BufferedImage(width, height, type); Graphics2D g = bi.createGraphics(); g.drawRenderedImage(image, new AffineTransform()); image = bi; } sampleModel = image.getSampleModel(); colorModel = image.getColorModel(); }
public BufferedImage crop(BufferedImage src, int left, int top, int width, int height) { int iw = src.getWidth(); int ih = src.getHeight(); if (left + width > iw) { width = iw - left; } if (top + height > ih) { height = ih - top; } ColorModel dstCM = src.getColorModel(); BufferedImage dst = new BufferedImage( dstCM, dstCM.createCompatibleWritableRaster(width, height), dstCM.isAlphaPremultiplied(), null); Graphics2D g = dst.createGraphics(); g.drawRenderedImage(src, AffineTransform.getTranslateInstance(-left, -top)); g.dispose(); return dst; }
public BufferedImage filter(BufferedImage src, BufferedImage dst) { int width = src.getWidth(); int height = src.getHeight(); if (dst == null) dst = new BufferedImage( width + leftBorder + rightBorder, height + topBorder + bottomBorder, src.getType()); Graphics2D g = dst.createGraphics(); if (borderPaint != null) { g.setPaint(borderPaint); if (leftBorder > 0) g.fillRect(0, 0, leftBorder, height); if (rightBorder > 0) g.fillRect(width - rightBorder, 0, rightBorder, height); if (topBorder > 0) g.fillRect(leftBorder, 0, width - leftBorder - rightBorder, topBorder); if (bottomBorder > 0) g.fillRect( leftBorder, height - bottomBorder, width - leftBorder - rightBorder, bottomBorder); } g.drawRenderedImage(src, AffineTransform.getTranslateInstance(leftBorder, rightBorder)); g.dispose(); return dst; }