List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:com.sketchy.utils.image.SketchyImage.java
public static BufferedImage toByteImage(BufferedImage image) { BufferedImage newImage = createByteImage(image.getWidth(), image.getHeight()); Graphics2D graphics = newImage.createGraphics(); graphics.setBackground(Color.white); graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); graphics.drawImage(image, 0, 0, null); return newImage; }
From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java
/** * Rotates the given buffered image by the given angle, and returns a newly * created image, containing the rotated image. * * @param img Image to rotate./*from www . ja va 2 s. c om*/ * @param angle Angle, in radians, by which to rotate the image. * @param drawOffset Receives the offset which is required to draw the image, * relative to the original (0,0) corner, so that the center of the image is * still on the same position. * * @return A newly created image containing the rotated image. */ public static BufferedImage rotateImage(BufferedImage img, float angle, Point drawOffset) { int w = img.getWidth(); int h = img.getHeight(); AffineTransform tf = AffineTransform.getRotateInstance(angle, w / 2.0, h / 2.0); // get coordinates for all corners to determine real image size Point2D[] ptSrc = new Point2D[4]; ptSrc[0] = new Point(0, 0); ptSrc[1] = new Point(w, 0); ptSrc[2] = new Point(w, h); ptSrc[3] = new Point(0, h); Point2D[] ptTgt = new Point2D[4]; tf.transform(ptSrc, 0, ptTgt, 0, ptSrc.length); Rectangle rc = new Rectangle(0, 0, w, h); for (Point2D p : ptTgt) { if (p.getX() < rc.x) { rc.width += rc.x - p.getX(); rc.x = (int) p.getX(); } if (p.getY() < rc.y) { rc.height += rc.y - p.getY(); rc.y = (int) p.getY(); } if (p.getX() > rc.x + rc.width) rc.width = (int) (p.getX() - rc.x); if (p.getY() > rc.y + rc.height) rc.height = (int) (p.getY() - rc.y); } BufferedImage imgTgt = new BufferedImage(rc.width, rc.height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = imgTgt.createGraphics(); // create a NEW rotation transformation around new center tf = AffineTransform.getRotateInstance(angle, rc.getWidth() / 2, rc.getHeight() / 2); g2d.setTransform(tf); g2d.drawImage(img, -rc.x, -rc.y, null); g2d.dispose(); drawOffset.x += rc.x; drawOffset.y += rc.y; return imgTgt; }
From source file:net.sf.mcf2pdf.mcfelements.util.ImageUtil.java
/** * Loads the given CLP or SVG file and creates a BufferedImage with the given dimensions. As CLP files contain Vector images, * they can be scaled to every size needed. The contents are scaled to the given width and height, <b>not</b> preserving any * ratio of the image./*w w w . j a va 2 s . c om*/ * * @param clpFile CLP or SVG file. * @param widthPixel The width, in pixels, the resulting image shall have. * @param heightPixel The height, in pixels, the resulting image shall have. * * @return An image displaying the contents of the loaded CLP file. * * @throws IOException If any I/O related problem occurs reading the file. */ public static BufferedImage loadClpFile(File clpFile, int widthPixel, int heightPixel) throws IOException { FileInputStream fis = new FileInputStream(clpFile); ClpInputStream cis = null; InputStream in = clpFile.getName().toLowerCase().endsWith(".clp") ? (cis = new ClpInputStream(fis)) : fis; UserAgentAdapter userAgentAdapter = new UserAgentAdapter(); BridgeContext bridgeContext = new BridgeContext(userAgentAdapter); SVGDocument svgDocument; GraphicsNode rootSvgNode; try { String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser); svgDocument = (SVGDocument) factory.createDocument(clpFile.toURI().toString(), new InputStreamReader(in, "ISO-8859-1")); rootSvgNode = getRootNode(svgDocument, bridgeContext); } finally { IOUtils.closeQuietly(cis); IOUtils.closeQuietly(fis); } float[] vb = ViewBox.parseViewBoxAttribute(svgDocument.getRootElement(), svgDocument.getRootElement().getAttribute("viewBox"), bridgeContext); AffineTransform usr2dev = ViewBox.getPreserveAspectRatioTransform(vb, SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_NONE, true, widthPixel, heightPixel); BufferedImage img = new BufferedImage(widthPixel, heightPixel, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = img.createGraphics(); g2d.setColor(new Color(0.0f, 0.0f, 0.0f, 0.0f)); g2d.fillRect(0, 0, widthPixel, heightPixel); g2d.transform(usr2dev); // fixes "Graphics2D from BufferedImage lacks BUFFERED_IMAGE hint" - part 1 final Object oldBufferedImage = g2d.getRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE); g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, new WeakReference<BufferedImage>(img)); rootSvgNode.paint(g2d); // fixes "Graphics2D from BufferedImage lacks BUFFERED_IMAGE hint" - part 2 if (oldBufferedImage != null) g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, oldBufferedImage); else g2d.getRenderingHints().remove(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE); g2d.dispose(); return img; }
From source file:fr.gael.dhus.datastore.processing.impl.ProcessingUtils.java
/** * Cut the quicklook that have a big width/height ratio. * Each sub-part is dispatched on multiple bands. * * @param quick_look the quick_look to be cut * @param max_ratio the maximum ratio between quick_look width and height. * @param margin the margin between each band. default 5. *///from www . ja va2s .c o m public static RenderedImage cutQuickLook(RenderedImage input_image, double max_ratio, int margin) { ColorModel color_model = input_image.getColorModel(); if ((color_model == null) && (input_image.getSampleModel() != null)) { color_model = ColorRenderer.createColorModel(input_image.getSampleModel()); } BufferedImage quick_look; try { quick_look = PlanarImage.wrapRenderedImage(input_image).getAsBufferedImage( new Rectangle(input_image.getWidth(), input_image.getHeight()), color_model); } catch (Exception e) { logger.error("Problem getting buffered image.", e); throw new IllegalArgumentException("Problem getting buffered image", e); } if ((quick_look != null) && ((quick_look.getWidth() > 0) && (quick_look.getHeight() > 0))) { //Compute width/height ratio int ql_width = quick_look.getWidth(); int ql_height = quick_look.getHeight(); int ratio = (int) Math.sqrt(Math.max(ql_width, ql_height) / Math.min(ql_width, ql_height)); //Check if the quicklook has a strong width/height ratio if ((ratio < max_ratio) || (ratio <= 1)) return PlanarImage.wrapRenderedImage(quick_look); /** * Cut the wider side (width or height) into "ratio" bands. * Ex: If height = 3 * width then we cut 3 bands along columns * So height' = height / 3 (extract 1 band / 3 from height) * width' = width * 3 (dispatch 3 bands along lines) */ int width = ql_width; //width of the bands int height = ql_height; //height of the bands if (ql_width < ql_height) //cut along height { width = (ql_width + margin) * ratio; height = ql_height / ratio; } else //cut along width { width = ql_width / ratio; height = (ql_height + margin) * ratio; } //Dispatch the sub-parts BufferedImage quick_look_cut = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = quick_look_cut.createGraphics(); for (int k = 0; k < ratio; k++) { BufferedImage ql_band = null; //Dispatch on columns if (ql_width < ql_height) { ql_band = quick_look.getSubimage(0, (k * ql_height) / ratio, ql_width, ql_height / ratio); g2.drawImage(ql_band, null, k * (ql_width + margin), 0); } //Dispatch on lines else { ql_band = quick_look.getSubimage((k * ql_width) / ratio, 0, ql_width / ratio, ql_height); g2.drawImage(ql_band, null, 0, k * (ql_height + margin)); } } //for each band g2.dispose(); return PlanarImage.wrapRenderedImage(quick_look_cut); } return PlanarImage.wrapRenderedImage(quick_look); }
From source file:editeurpanovisu.ReadWriteImage.java
public static void writeTiff(Image imgImage, String strNomFich, boolean bSharpen, float sharpenLevel) throws ImageReadException, IOException { File file = new File(strNomFich); BufferedImage imageRGBSharpen = null; BufferedImage imageRGB = SwingFXUtils.fromFXImage(imgImage, null); Graphics2D graphics = imageRGB.createGraphics(); graphics.drawImage(imageRGB, 0, 0, null); if (bSharpen) { imageRGBSharpen = new BufferedImage(imageRGB.getWidth(), imageRGB.getHeight(), BufferedImage.TYPE_INT_RGB); Kernel kernel = new Kernel(3, 3, sharpenMatrix); ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); cop.filter(imageRGB, imageRGBSharpen); }/*from w w w.j a va2 s . co m*/ final ImageFormat format = ImageFormats.TIFF; final Map<String, Object> params = new HashMap<>(); params.put(ImagingConstants.PARAM_KEY_COMPRESSION, new Integer(TiffConstants.TIFF_COMPRESSION_UNCOMPRESSED)); if (bSharpen) { try { Imaging.writeImage(imageRGBSharpen, file, format, params); } catch (ImageWriteException ex) { Logger.getLogger(ReadWriteImage.class.getName()).log(Level.SEVERE, null, ex); } } else { try { Imaging.writeImage(imageRGB, file, format, params); } catch (ImageWriteException ex) { Logger.getLogger(ReadWriteImage.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:common.utils.ImageUtils.java
/** * * @param src images to draw, they must be resized to an appropriate size * @param dst image where given images will be drawen */// w w w. ja va 2 s . c om public static void draw4on1(BufferedImage[] src, BufferedImage dst) { Graphics2D g2 = dst.createGraphics(); g2.setColor(java.awt.Color.WHITE); g2.fillRect(0, 0, dst.getWidth(), dst.getHeight()); int dxi; int dyi = 0; int x0 = dst.getWidth() - 5; int y0 = 5; int x = x0; int y = y0; for (int i = 0; i < src.length; i++) { if (i % 2 == 0) { dxi = -10; } else { dxi = 0; } //g2.draw3DRect(dx - 1 , dy-tmp_bi.getHeight() - 1, tmp_bi.getWidth() + 1 , tmp_bi.getHeight() + 1, true); g2.drawImage(src[i], x - src[i].getWidth() + dxi, y + dyi, null); g2.drawString("#" + i, x - src[i].getWidth() + dxi, y + dyi + 20); //g2.rotate(Math.toRadians(4)); y = y + src[i].getHeight() / 2; if (y > dst.getHeight() - src[i].getHeight()) { y = y0; if (dyi == 0) dyi = 10; else dyi = 0; if (x < src[i].getWidth()) { x = dst.getWidth(); } x = x - src[i].getWidth() / 2; } } g2.setColor(Color.gray); g2.drawRect(0, 0, dst.getWidth() - 1, dst.getHeight() - 1); g2.dispose(); }
From source file:common.utils.ImageUtils.java
/** * resize input image to new dinesions(only smaller) into rez parameter * @param image input image for scaling * @param rez resulting image. must have required width and height * @throws IOException/* w w w. ja v a 2 s .c om*/ */ public static void getScaledImageDimmension(BufferedImage image, BufferedImage rez) throws IOException { Graphics2D g2 = rez.createGraphics(); if (rez.getHeight() > image.getHeight() || rez.getWidth() > image.getWidth()) { //rez image is bigger no resize g2.drawImage(image, 0, 0, null); return; } //1-st getting first side to resize (width or height) double scale_factor; if (getScaling(image.getHeight(), rez.getHeight()) > getScaling(image.getWidth(), rez.getWidth())) { //resize height scale_factor = getScaling(image.getHeight(), rez.getHeight()); int width = (int) (scale_factor * image.getWidth()); //cut width int x = (rez.getWidth() - width) / 2; g2.drawImage(image.getScaledInstance(width, rez.getHeight(), Image.SCALE_SMOOTH), x, 0, null); //System.out.println("resizing height: h="+image.getHeight()+"/"+rez.getHeight()+"; x="+x); } else { //resize width scale_factor = getScaling(image.getWidth(), rez.getWidth()); int height = (int) (scale_factor * image.getHeight()); //cut height int y = (rez.getHeight() - height) / 2; g2.drawImage(image.getScaledInstance(rez.getWidth(), height, Image.SCALE_SMOOTH), 0, y, null); //System.out.println("resizing width: w="+image.getWidth()+"/"+rez.getWidth()+"; y="+y); } g2.dispose(); }
From source file:com.sun.socialsite.util.ImageUtil.java
public static BufferedImage getScaledImage(BufferedImage origImage, Integer desiredWidth, Integer desiredHeight) throws IOException { if (origImage == null) { return null; }/*from ww w . j av a2 s . c o m*/ if (desiredWidth == null) { desiredWidth = origImage.getWidth(); } if (desiredHeight == null) { desiredHeight = origImage.getHeight(); } int origWidth = origImage.getWidth(); int origHeight = origImage.getHeight(); double ratio = Math.min((((double) desiredWidth) / origWidth), (((double) desiredHeight) / origHeight)); int extraWidth = desiredWidth - ((int) (origWidth * ratio)); int extraHeight = desiredHeight - ((int) (origHeight * ratio)); int tmpWidth = (desiredWidth - extraWidth); int tmpHeight = (desiredHeight - extraHeight); BufferedImage tmpImage = getScaledInstance(origImage, tmpWidth, tmpHeight, RenderingHints.VALUE_INTERPOLATION_BICUBIC, true); log.debug(String.format("tmpImage[width=%d height=%d", tmpImage.getWidth(), tmpImage.getHeight())); if ((tmpImage.getWidth() == desiredWidth) && (tmpImage.getHeight() == desiredHeight)) { return tmpImage; } else { BufferedImage scaledImage = new BufferedImage(desiredWidth, desiredHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = scaledImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); // We recalculate these in case scaling didn't quite hit its targets extraWidth = desiredWidth - tmpImage.getWidth(); extraHeight = desiredHeight - tmpImage.getHeight(); int dx1 = extraWidth / 2; int dy1 = extraHeight / 2; int dx2 = desiredWidth - dx1; int dy2 = desiredWidth - dy1; // transparent background g2d.setColor(new Color(0, 0, 0, 0)); g2d.fillRect(0, 0, desiredWidth, desiredHeight); g2d.drawImage(tmpImage, dx1, dy1, dx2, dy2, null); return scaledImage; } }
From source file:imageLines.ImageHelpers.java
/**Scale an image to the specified width and height*/ public static BufferedImage scale(BufferedImage img, int height, int width) { BufferedImage bdest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bdest.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance((double) width / img.getWidth(), (double) height / img.getHeight()); g.drawRenderedImage(img, at);/*from w ww . j a va2s . c o m*/ return bdest; }
From source file:juicebox.tools.utils.juicer.apa.APAPlotter.java
/** * Method for plotting apa data/*from w w w. j a v a2s . c o m*/ * * @param data for heat map * @param axesRange initial values and increments to annotate axes [x0, dx, y0, dy] * @param outputFile where image will saved */ public static void plot(RealMatrix data, int[] axesRange, File outputFile, String title) { APARegionStatistics apaStats = new APARegionStatistics(data); DecimalFormat df = new DecimalFormat("0.000"); title += ", P2LL = " + df.format(apaStats.getPeak2LL()); // initialize heat map HeatChart map = new HeatChart(data.getData()); map.setLowValueColour(Color.WHITE); map.setHighValueColour(Color.RED); map.setXValues(axesRange[0], axesRange[1]); map.setYValues(axesRange[2], axesRange[3]); map.setTitle(title); try { // calculate dimensions for plot wrapper initializeSizes(map); // create blank white image BufferedImage apaImage = new BufferedImage(fullWidth, fullHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = apaImage.createGraphics(); g2.setBackground(Color.WHITE); g2.fillRect(0, 0, fullWidth, fullHeight); // plot in heat map, color bar, etc g2.drawImage(map.getChartImage(), 0, 0, heatmapWidth, fullHeight, null); drawHeatMapBorder(g2, map); plotColorScaleBar(g2); plotColorScaleValues(g2, map); // top left, top right, bottom left, bottom right values (from apa) drawCornerRegions(g2, map, new Dimension(APA.regionWidth, APA.regionWidth), apaStats.getRegionCornerValues()); // save data ImageIO.write(apaImage, "png", outputFile); } catch (IOException e) { e.printStackTrace(); } }