List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:de.thm.arsnova.ImageUtils.java
/** * Rescales an image represented by a Base64-encoded {@link String} * * @param originalImageString/*from www. ja va 2 s . co m*/ * The original image represented by a Base64-encoded * {@link String} * @param width * the new width * @param height * the new height * @return The rescaled Image as Base64-encoded {@link String}, returns null * if the passed-on image isn't in a valid format (a Base64-Image). */ public String createCover(String originalImageString, final int width, final int height) { if (!isBase64EncodedImage(originalImageString)) { return null; } else { final String[] imgInfo = extractImageInfo(originalImageString); // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method final String extension = imgInfo[0]; final String base64String = imgInfo[1]; byte[] imageData = Base64.decodeBase64(base64String); try { BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData)); BufferedImage newImage = new BufferedImage(width, height, originalImage.getType()); Graphics2D g = newImage.createGraphics(); final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight()); int x = 0, y = 0, w = width, h = height; if (originalImage.getWidth() > originalImage.getHeight()) { final int newWidth = (int) Math.round((float) height * ratio); x = -(newWidth - width) >> 1; w = newWidth; } else if (originalImage.getWidth() < originalImage.getHeight()) { final int newHeight = (int) Math.round((float) width / ratio); y = -(newHeight - height) >> 1; h = newHeight; } g.drawImage(originalImage, x, y, w, h, null); g.dispose(); StringBuilder result = new StringBuilder(); result.append("data:image/"); result.append(extension); result.append(";base64,"); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(newImage, extension, output); output.flush(); output.close(); result.append(Base64.encodeBase64String(output.toByteArray())); return result.toString(); } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); return null; } } }
From source file:org.gumtree.vis.mask.ChartTransferableWithMask.java
@Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { BufferedImage image; if (this.imageFlavor.equals(flavor)) { image = chart.createBufferedImage(width, height); } else {/*w w w . j av a2s .com*/ throw new UnsupportedFlavorException(flavor); } Graphics2D g2 = image.createGraphics(); drawMasksInDataArea(g2, dataArea != null ? dataArea : new Rectangle2D.Double(0, 0, width, height), masks, chart); ChartMaskingUtilities.drawShapes(g2, dataArea, shapeMap, chart); ChartMaskingUtilities.drawText(g2, dataArea, textContentMap, chart); g2.dispose(); return image; }
From source file:SimpleBufferedImageDemo.java
public void paint(Graphics g) { Graphics2D g2D = (Graphics2D) g; if (display) { if (buffered) { BufferedImage bi = (BufferedImage) createImage(getWidth(), getHeight()); // Draw into the memory buffer. for (int i = 0; i < getWidth(); i = i + displayImage.getWidth(this)) { for (int j = 0; j < getHeight(); j = j + displayImage.getHeight(this)) { bi.createGraphics().drawImage(displayImage, i, j, this); }//from w w w . j a va 2s .c om } // Draw the buffered Image on to the screen g2D.drawImage(bi, 0, 0, this); } // This block of code draws the texture directly onto the screen. else if (!buffered) { for (int i = 0; i < getWidth(); i = i + displayImage.getWidth(this)) { for (int j = 0; j < getHeight(); j = j + displayImage.getHeight(this)) { g2D.drawImage(displayImage, i, j, this); } } } display = false; } else if (clear) { g2D.setColor(Color.white); g2D.clearRect(0, 0, getWidth(), getHeight()); clear = false; } }
From source file:net.refractions.udig.catalog.wmsc.server.AbstractTileRange.java
protected BufferedImage createErrorImage() { BufferedImage bf = new BufferedImage(tileset.getWidth(), tileset.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = bf.createGraphics(); g.setColor(Color.RED);//from w w w .j a v a 2 s . co m g.drawLine(0, 0, tileset.getWidth(), tileset.getHeight()); g.drawLine(0, tileset.getHeight(), tileset.getWidth(), 0); return bf; }
From source file:br.prof.salesfilho.oci.image.ImageProcessor.java
public BufferedImage resize(int newWidth, int newHeigth) { Image tmp = image.getScaledInstance(newWidth, newHeigth, Image.SCALE_SMOOTH); BufferedImage dimg = new BufferedImage(newWidth, newHeigth, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null);/* w w w.j a v a2 s.c o m*/ g2d.dispose(); this.image = dimg; return this.image; }
From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java
private static <S extends Shape> void plotLocal(Path inFile, Path outFile, OperationsParams params) throws IOException { int width = params.getInt("width", 1000); int height = params.getInt("height", 1000); Color strokeColor = params.getColor("color", Color.BLACK); int color = strokeColor.getRGB(); String hdfDataset = (String) params.get("dataset"); Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null); Shape plotRange = params.getShape("rect", null); boolean keepAspectRatio = params.is("keep-ratio", true); String valueRangeStr = (String) params.get("valuerange"); MinMax valueRange;/*from w ww . ja v a2 s .com*/ if (valueRangeStr == null) { valueRange = null; } else { String[] parts = valueRangeStr.split(","); valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); } InputSplit[] splits; FileSystem inFs = inFile.getFileSystem(params); FileStatus inFStatus = inFs.getFileStatus(inFile); if (inFStatus != null && !inFStatus.isDir()) { // One file, retrieve it immediately. // This is useful if the input is a hidden file which is automatically // skipped by FileInputFormat. We need to plot a hidden file for the case // of plotting partition boundaries of a spatial index splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) }; } else { JobConf job = new JobConf(params); ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>(); ShapeInputFormat.addInputPath(job, inFile); splits = inputFormat.getSplits(job, 1); } boolean vflip = params.is("vflip"); Rectangle fileMbr; if (plotRange != null) { fileMbr = plotRange.getMBR(); } else if (hdfDataset != null) { // Plotting a NASA file fileMbr = new Rectangle(-180, -90, 180, 90); } else { fileMbr = FileMBR.fileMBR(inFile, params); } if (keepAspectRatio) { // Adjust width and height to maintain aspect ratio if (fileMbr.getWidth() / fileMbr.getHeight() > (double) width / height) { // Fix width and change height height = (int) (fileMbr.getHeight() * width / fileMbr.getWidth()); } else { width = (int) (fileMbr.getWidth() * height / fileMbr.getHeight()); } } boolean adaptiveSample = shape instanceof Point && params.getBoolean("sample", false); float adaptiveSampleRatio = 0.0f; if (adaptiveSample) { // Calculate the sample ratio long recordCount = FileMBR.fileMBR(inFile, params).recordCount; adaptiveSampleRatio = params.getFloat(AdaptiveSampleFactor, 1.0f) * width * height / recordCount; } boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false); if (hdfDataset != null) { // Collects some stats about the HDF file if (valueRange == null) valueRange = Aggregate.aggregate(new Path[] { inFile }, params); NASAPoint.minValue = valueRange.minValue; NASAPoint.maxValue = valueRange.maxValue; NASAPoint.setColor1(params.getColor("color1", Color.BLUE)); NASAPoint.setColor2(params.getColor("color2", Color.RED)); NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE); } double scale2 = (double) width * height / (fileMbr.getWidth() * fileMbr.getHeight()); double scale = Math.sqrt(scale2); // Create an image BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); Color bg_color = params.getColor("bgcolor", new Color(0, 0, 0, 0)); graphics.setBackground(bg_color); graphics.clearRect(0, 0, width, height); graphics.setColor(strokeColor); for (InputSplit split : splits) { if (hdfDataset != null) { // Read points from the HDF file RecordReader<NASADataset, NASAShape> reader = new HDFRecordReader(params, (FileSplit) split, hdfDataset, true); NASADataset dataset = reader.createKey(); while (reader.next(dataset, (NASAShape) shape)) { // Skip with a fixed ratio if adaptive sample is set if (adaptiveSample && Math.random() > adaptiveSampleRatio) continue; if (plotRange == null || shape.isIntersected(shape)) { shape.draw(graphics, fileMbr, width, height, 0.0); } } reader.close(); } else { RecordReader<Rectangle, Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split); Rectangle cell = reader.createKey(); while (reader.next(cell, shape)) { // Skip with a fixed ratio if adaptive sample is set if (adaptiveSample && Math.random() > adaptiveSampleRatio) continue; Rectangle shapeMBR = shape.getMBR(); if (shapeMBR != null) { if (plotRange == null || shapeMBR.isIntersected(plotRange)) { if (gradualFade) { double sizeInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight()) * scale; if (sizeInPixels < 1.0 && Math.round(sizeInPixels * 255) < 1.0) { // This shape can be safely skipped as it is too small to be plotted continue; } else { int alpha = (int) Math.round(sizeInPixels * 255); graphics.setColor(new Color((alpha << 24) | color, true)); } } shape.draw(graphics, fileMbr, width, height, scale2); } } } reader.close(); } } // Write image to output graphics.dispose(); if (vflip) { AffineTransform tx = AffineTransform.getScaleInstance(1, -1); tx.translate(0, -image.getHeight()); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR); image = op.filter(image, null); } FileSystem outFs = outFile.getFileSystem(params); OutputStream out = outFs.create(outFile, true); ImageIO.write(image, "png", out); out.close(); }
From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java
/** * Creates a thumbnail for the image file using plain old java * @param file the image file/*from w ww .j a v a 2s . co m*/ * @param thumbFile the resulting thumbnail file * @param size the size of the thumbnail */ private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException { try { BufferedImage image = ImageIO.read(file.toFile()); int w = image.getWidth(); int h = image.getHeight(); // Never scale up if (w <= size.getSize() && h <= size.getSize()) { FileUtils.copyFile(file.toFile(), thumbFile.toFile()); } else { // Compute the scale factor double dx = (double) size.getSize() / (double) w; double dy = (double) size.getSize() / (double) h; double d = Math.min(dx, dy); // Create the thumbnail BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = thumbImage.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance(d, d); g2d.drawRenderedImage(image, at); g2d.dispose(); // Save the thumbnail String fileName = thumbFile.getFileName().toString(); ImageIO.write(thumbImage, FilenameUtils.getExtension(fileName), thumbFile.toFile()); // Releas resources image.flush(); thumbImage.flush(); } // Update the timestamp of the thumbnail file to match the change date of the image file Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file)); } catch (Exception e) { log.error("Error creating thumbnail for image " + file, e); throw new IOException(e); } }
From source file:com.bwc.ora.models.Lrp.java
@Override public void drawOverlay(BufferedImage baseImg) { Graphics2D graphics = baseImg.createGraphics(); graphics.setColor(Color.green); graphics.draw(this); // System.out.println("Drawing selection on OCT..."); }
From source file:com.iontorrent.vaadin.utils.JFreeChartWrapper.java
public ChartRenderingInfo getInfo(int w, int h) { info = new ChartRenderingInfo(); BufferedImage img = chart.createBufferedImage(w, h, info); Graphics2D g = img.createGraphics(); chart.draw(g, new Rectangle(w, h), info); return info;/*from w w w . j a va 2 s . c o m*/ }
From source file:TexturedPanel.java
/** * Creates a new TexturePaint using the provided colors and texture map. *//*from w ww . j a v a2s. c o m*/ private void setupTexturePainter(Color foreground, Color background, boolean[][] texture, int scale) { if (texture == null || texture.length < 1 || texture[0].length < 1) { setupDefaultPainter(foreground, background); return; } else if (foreground == null || background == null) { ourPainter = null; return; } scale = Math.max(1, scale); int w = texture[0].length; int h = texture.length; BufferedImage buff = new BufferedImage(w * scale, h * scale, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = buff.createGraphics(); g2.setColor(background); g2.fillRect(0, 0, w * scale, h * scale); g2.setColor(foreground); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { try { if (texture[i][j]) g2.fillRect(j * scale, i * scale, scale, scale); } // g2.drawLine(j, i, j, i); } catch (ArrayIndexOutOfBoundsException aob) { } } } ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w * scale, h * scale)); g2.dispose(); }