List of usage examples for java.awt.image BufferedImage createGraphics
public Graphics2D createGraphics()
From source file:com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java
private void cleanImage(BufferedImage image, List<Rectangle> areasToBeCleaned) { Graphics2D graphics = image.createGraphics(); graphics.setColor(CLEANED_AREA_FILL_COLOR); // A rectangle in the areasToBeCleaned list is treated to be in standard [0, 1]x[0,1] image space // (y varies from bottom to top and x from left to right), so we should scale the rectangle and also // invert and shear the y axe for (Rectangle rect : areasToBeCleaned) { int scaledBottomY = (int) Math.ceil(rect.getBottom() * image.getHeight()); int scaledTopY = (int) Math.floor(rect.getTop() * image.getHeight()); int x = (int) Math.ceil(rect.getLeft() * image.getWidth()); int y = scaledTopY * -1 + image.getHeight(); int width = (int) Math.floor(rect.getRight() * image.getWidth()) - x; int height = scaledTopY - scaledBottomY; graphics.fillRect(x, y, width, height); }/*from ww w .j a v a2s . c o m*/ graphics.dispose(); }
From source file:com.neophob.sematrix.core.generator.Textwriter.java
/** * create image.// w ww.j ava 2s. com * * @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:org.yamj.core.service.file.FileStorageService.java
public void storeImage(String filename, StorageType type, BufferedImage bi, ImageFormat imageFormat, int quality) throws Exception { LOG.debug("Store {} {} image: {}", type, imageFormat, filename); String storageFileName = getStorageName(type, filename); File outputFile = new File(storageFileName); ImageWriter writer = null;// w ww . j av a 2s.co m FileImageOutputStream output = null; try { if (ImageFormat.PNG == imageFormat) { ImageIO.write(bi, "png", outputFile); } else { float jpegQuality = (float) quality / 100; BufferedImage bufImage = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB); bufImage.createGraphics().drawImage(bi, 0, 0, null, null); @SuppressWarnings("rawtypes") Iterator iter = ImageIO.getImageWritersByFormatName("jpeg"); writer = (ImageWriter) iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(jpegQuality); output = new FileImageOutputStream(outputFile); writer.setOutput(output); IIOImage image = new IIOImage(bufImage, null, null); writer.write(null, image, iwp); } } finally { if (writer != null) { writer.dispose(); } if (output != null) { try { output.close(); } catch (IOException ex) { LOG.trace("Failed to close stream: {}", ex.getMessage(), ex); } } } }
From source file:com.joliciel.jochre.graphics.VectorizerImpl.java
public BufferedImage drawArrayLists(JochreImage jochreImage) { long startTime = (new Date()).getTime(); BufferedImage vectorizedImage = new BufferedImage(jochreImage.getWidth(), jochreImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics2D = vectorizedImage.createGraphics(); graphics2D.setStroke(new BasicStroke(1)); graphics2D.setPaint(Color.BLACK); for (Paragraph paragraph : jochreImage.getParagraphs()) { for (RowOfShapes row : paragraph.getRows()) { for (GroupOfShapes group : row.getGroups()) { for (Shape shape : group.getShapes()) { List<LineSegment> lines = this.vectorize(shape); for (LineSegment line : lines) graphics2D.drawLine(shape.getLeft() + line.getStartX(), shape.getTop() + line.getStartY(), shape.getLeft() + line.getEndX(), shape.getTop() + line.getEndY()); }/*from w w w.j a va 2s . c o m*/ } } } if (LOG.isDebugEnabled()) { long endTime = (new Date()).getTime(); long diff = endTime - startTime; LOG.debug("Time elapsed: " + ((double) diff / 1000)); } return vectorizedImage; }
From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java
/** * Rescales using arbitrary intensities and converts to 8bit. Works for gray- and rgb color images. * * @param bi16//from w w w . j a va 2 s . c o m * @return */ public static BufferedImage convertTo8bit(BufferedImage bi16, double intScalingMin, double intScalignMax) { // TODO: use min,max from plate meta data, not image specific int[][] minMax = ImageUtils.getMinMaxIntensitiesOfBI(bi16); BufferedImage bi = null; if (bi16.getSampleModel().getNumBands() == 1) { bi16 = ImageUtils.scaleIntensities(bi16, getPercentileIntensity(bi16, intScalingMin), getPercentileIntensity(bi16, intScalignMax)); bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_BYTE_GRAY); } else if (bi16.getSampleModel().getNumBands() == 3) { bi16 = ImageUtils.scaleIntensities(bi16, getPercentileIntensity(bi16, intScalingMin), getPercentileIntensity(bi16, intScalignMax)); bi = new BufferedImage(bi16.getWidth(), bi16.getHeight(), BufferedImage.TYPE_INT_RGB); } else { throw new IllegalArgumentException( "Only images with 1 band (gray-color) or 3 bands (rgb) supported. This image has " + bi16.getSampleModel().getNumBands() + " bands."); } Graphics2D g2d = bi.createGraphics(); g2d.drawImage(bi16, 0, 0, null); g2d.dispose(); return bi; }
From source file:org.iish.visualmets.services.ImageTransformation.java
/** * Returns a scaled BufferedImage/* www. ja v a 2 s .c om*/ * * @param bi current image * @param maxWidth new width * @param maxHeight new height * @return a new/scaled image */ /*public static BufferedImage ScaleImage(BufferedImage image, int width, int height) throws IOException { int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); double scaleX = (double)width/imageWidth; double scaleY = (double)height/imageHeight; AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY); AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR); return bilinearScaleOp.filter( image, new BufferedImage(width, height, image.getType())); }*/ public BufferedImage ScaleImage(BufferedImage bi, int maxWidth, int maxHeight) { double originalWidth = bi.getWidth() * 1.0; double originalHeight = bi.getHeight() * 1.0; double widthRatio = (maxWidth * 1.0) / originalWidth; double heightRatio = (maxHeight * 1.0) / originalHeight; double newImageRatio = 0; if (widthRatio < heightRatio) { newImageRatio = widthRatio; } else { newImageRatio = heightRatio; } BufferedImage bdest = new BufferedImage((int) (originalWidth * newImageRatio), (int) (originalHeight * newImageRatio), BufferedImage.TYPE_INT_RGB); Graphics2D g = bdest.createGraphics(); AffineTransform at = AffineTransform.getScaleInstance(newImageRatio, newImageRatio); g.drawRenderedImage(bi, at); return bdest; }
From source file:bachelorthesis.captchabuilder.builder.CaptchaBuilder.java
private BufferedImage flattenImage() { BufferedImage rImage; if (bg == null) { rImage = new BackgroundProducerBuilder(BackgroundProducerType.TRANSPARENT).create() .getBackground(img.getWidth(), img.getHeight()); } else {/*from ww w .ja v a 2 s . c o m*/ rImage = bg; } // Paint the main image over the background Graphics2D g = rImage.createGraphics(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g.drawImage(img, null, null); return rImage; }
From source file:com.t3.client.TabletopTool.java
public static BufferedImage takeMapScreenShot(final PlayerView view) { final ZoneRenderer renderer = clientFrame.getCurrentZoneRenderer(); if (renderer == null) { return null; }/* w ww. ja v a2 s. c om*/ Dimension size = renderer.getSize(); if (size.width == 0 || size.height == 0) { return null; } BufferedImage image = new BufferedImage(size.width, size.height, Transparency.OPAQUE); final Graphics2D g = image.createGraphics(); g.setClip(0, 0, size.width, size.height); // Have to do this on the EDT so that there aren't any odd side effects // of rendering // using a renderer that's on screen if (!EventQueue.isDispatchThread()) { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { renderer.renderZone(g, view); } }); } catch (InterruptedException ie) { TabletopTool.showError("While creating snapshot", ie); } catch (InvocationTargetException ite) { TabletopTool.showError("While creating snapshot", ite); } } else { renderer.renderZone(g, view); } g.dispose(); return image; }
From source file:de.romankreisel.faktotum.beans.BundesbruderBean.java
public void rotateProfilePictureClockwise(BundesbruderEntity bundesbruder, double angle) throws IOException { BufferedImage image = this.getImageFromByteArray(bundesbruder.getPictureOriginal()); 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); GraphicsConfiguration gc = image.createGraphics().getDeviceConfiguration(); BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT); Graphics2D g = result.createGraphics(); g.translate((neww - w) / 2, (newh - h) / 2); g.rotate(angle, w / 2, h / 2);// www .j a v a2 s.c om g.drawRenderedImage(image, null); g.dispose(); this.setProfilePicture(bundesbruder, this.storeImageToByteArray(image)); }
From source file:org.jrecruiter.service.impl.DataServiceImpl.java
/** {@inheritDoc} */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public Image getGoogleMapImage(final BigDecimal latitude, final BigDecimal longitude, final Integer zoomLevel) { if (longitude == null) { throw new IllegalArgumentException("Longitude cannot be null."); }//from w w w. j a v a 2s . co m if (latitude == null) { throw new IllegalArgumentException("Latitude cannot be null."); } if (zoomLevel == null) { throw new IllegalArgumentException("ZoomLevel cannot be null."); } final URI url = GoogleMapsUtils.buildGoogleMapsStaticUrl(latitude, longitude, zoomLevel); BufferedImage img; try { URLConnection conn = url.toURL().openConnection(); img = ImageIO.read(conn.getInputStream()); } catch (UnknownHostException e) { LOGGER.error("Google static MAPS web service is not reachable (UnknownHostException).", e); img = new BufferedImage(GoogleMapsUtils.defaultWidth, 100, BufferedImage.TYPE_INT_RGB); final Graphics2D graphics = img.createGraphics(); final Map<Object, Object> renderingHints = CollectionUtils.getHashMap(); renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics.addRenderingHints(renderingHints); graphics.setBackground(Color.WHITE); graphics.setColor(Color.GRAY); graphics.clearRect(0, 0, GoogleMapsUtils.defaultWidth, 100); graphics.drawString("Not Available", 30, 30); } catch (IOException e) { throw new IllegalStateException(e); } return img; }