List of usage examples for java.awt.image BufferedImage getGraphics
public java.awt.Graphics getGraphics()
From source file:business.model.CaptchaModel.java
/** * * @param baseImage// www . ja v a 2 s . c o m * @return */ private static BufferedImage getDistortedImage(BufferedImage baseImage) { BufferedImage distortedImage = new BufferedImage(baseImage.getWidth(), baseImage.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D graph = (Graphics2D) distortedImage.getGraphics(); ShadowFilter shadowFilter = new ShadowFilter(); shadowFilter.setRadius(10); shadowFilter.setDistance(5); shadowFilter.setOpacity(1); Random rand = new Random(); RippleFilter rippleFilter = new RippleFilter(); rippleFilter.setWaveType(RippleFilter.SINE); rippleFilter.setXAmplitude(1.6f); rippleFilter.setYAmplitude(1.0f); rippleFilter.setXWavelength(5); rippleFilter.setYWavelength(2); rippleFilter.setEdgeAction(TransformFilter.BILINEAR); BufferedImage effectImage = rippleFilter.filter(baseImage, null); effectImage = shadowFilter.filter(effectImage, null); graph.drawImage(effectImage, 0, 0, null, null); graph.dispose(); // draw lines over the image and/or text // noiseProducer.makeNoise(distortedImage, .1f, .1f, .25f, .25f); return distortedImage; }
From source file:com.boundlessgeo.geoserver.api.controllers.ThumbnailController.java
/** * Utility method for scaling thumbnails. Scales byte[] image by a scale factor. * Optionally crops images to square.//from w w w. ja va 2 s . c o m * @param src RenderedImage containing the input image * @param scale Scale amount * @param square Boolean flag to crop to a square image * @return RenderedImage containing the transformed image * @throws IOException */ public static BufferedImage scaleImage(BufferedImage image, double scale, boolean square) throws IOException { int sx = 0, sy = 0; int swidth = image.getWidth(); int sheight = image.getHeight(); if (square) { if (image.getHeight() > image.getWidth()) { sy = (int) ((image.getHeight() - image.getWidth()) / 2.0); sheight = swidth; } else if (image.getHeight() < image.getWidth()) { sx = (int) ((image.getWidth() - image.getHeight()) / 2.0); swidth = sheight; } } int width = (int) (swidth * scale); int height = (int) (sheight * scale); BufferedImage scaled = new BufferedImage(image.getColorModel(), image.getRaster().createCompatibleWritableRaster(width, height), image.isAlphaPremultiplied(), null); Graphics g = scaled.getGraphics(); g.drawImage(image, 0, 0, width, height, sx, sy, sx + swidth, sy + sheight, null); g.dispose(); return scaled; }
From source file:de.mpg.imeji.logic.storage.util.ImageUtils.java
/** * Scale a {@link BufferedImage} to new size. Is faster than the basic {@link ImageUtils}.scaleImage method, has the * same quality. If it is a thumbnail, cut the images to fit into the raster * /* w w w . jav a 2 s .co m*/ * @param image original image * @param size the size to be resized to * @param resolution the type of the image. Might be thumb or web * @return the resized images * @throws Exception */ public static BufferedImage scaleImageFast(BufferedImage image, int size, FileResolution resolution) throws Exception { int width = image.getWidth(null); int height = image.getHeight(null); BufferedImage newImg = null; Image rescaledImage; if (width > height) { if (FileResolution.THUMBNAIL.equals(resolution)) { newImg = new BufferedImage(height, height, BufferedImage.TYPE_INT_RGB); Graphics g1 = newImg.createGraphics(); g1.drawImage(image, (height - width) / 2, 0, null); if (height > size) rescaledImage = getScaledInstance(newImg, size, size, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); else rescaledImage = newImg; } else rescaledImage = getScaledInstance(image, size, height * size / width, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); } else { if (FileResolution.THUMBNAIL.equals(resolution)) { newImg = new BufferedImage(width, width, BufferedImage.TYPE_INT_RGB); Graphics g1 = newImg.createGraphics(); g1.drawImage(image, 0, (width - height) / 2, null); if (width > size) rescaledImage = getScaledInstance(newImg, size, size, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); else rescaledImage = newImg; } else rescaledImage = getScaledInstance(image, width * size / height, size, RenderingHints.VALUE_INTERPOLATION_BILINEAR, RESCALE_HIGH_QUALITY); } BufferedImage rescaledBufferedImage = new BufferedImage(rescaledImage.getWidth(null), rescaledImage.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics g2 = rescaledBufferedImage.getGraphics(); g2.drawImage(rescaledImage, 0, 0, null); return rescaledBufferedImage; }
From source file:org.uva.itast.blended.omr.BufferedImageUtil.java
/** * Rotates 90, -90 deegrees// w w w . j ava 2 s .com * @param imageToRotate * @param degrees 90 or -90 rotation. * @return */ public static BufferedImage rotateImage(BufferedImage imageToRotate, float degrees) { if (degrees != 90.0 && degrees != -90.0) throw new IllegalArgumentException("Only implemented +90 and -90 rotation"); BufferedImage rotatedImage = new BufferedImage(imageToRotate.getHeight(null), imageToRotate.getWidth(null), imageToRotate.getType()); Graphics2D g2d = (Graphics2D) rotatedImage.getGraphics(); g2d.rotate(Math.toRadians(degrees)); g2d.drawImage(imageToRotate, 0, -rotatedImage.getWidth(null), null); return rotatedImage; }
From source file:net.semanticmetadata.lire.utils.FileUtils.java
public static void saveImageResultsToPng(String prefix, TopDocs hits, String queryImage, IndexReader ir) throws IOException { LinkedList<BufferedImage> results = new LinkedList<BufferedImage>(); int width = 0; for (int i = 0; i < Math.min(hits.scoreDocs.length, 10); i++) { // hits.score(i) // hits.doc(i).get("descriptorImageIdentifier") BufferedImage tmp = ImageIO .read(new FileInputStream(ir.document(hits.scoreDocs[i].doc).get("descriptorImageIdentifier"))); if (tmp.getHeight() > 200) { double factor = 200d / ((double) tmp.getHeight()); tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200); }/*from w ww .j av a 2s. c o m*/ width += tmp.getWidth() + 5; results.add(tmp); } BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) result.getGraphics(); g2.setColor(Color.black); g2.clearRect(0, 0, result.getWidth(), result.getHeight()); g2.setColor(Color.green); g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12")); int offset = 0; int count = 0; for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) { BufferedImage next = iterator.next(); g2.drawImage(next, offset, 20, null); g2.drawString(hits.scoreDocs[count].score + "", offset + 5, 12); offset += next.getWidth() + 5; count++; } ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png")); }
From source file:net.semanticmetadata.lire.utils.FileUtils.java
public static void saveImageResultsToPng(String prefix, ImageSearchHits hits, String queryImage, IndexReader reader) throws IOException { LinkedList<BufferedImage> results = new LinkedList<BufferedImage>(); int width = 0; for (int i = 0; i < hits.length(); i++) { // hits.score(i) // hits.doc(i).get("descriptorImageIdentifier") BufferedImage tmp = ImageIO.read(new FileInputStream( reader.document(hits.documentID(i)).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0])); // if (tmp.getHeight() > 200) { double factor = 200d / ((double) tmp.getHeight()); tmp = ImageUtils.scaleImage(tmp, (int) (tmp.getWidth() * factor), 200); // } width += tmp.getWidth() + 5;/*from w ww. j a va2s. c o m*/ results.add(tmp); } BufferedImage result = new BufferedImage(width, 220, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) result.getGraphics(); g2.setColor(Color.white); g2.setBackground(Color.white); g2.clearRect(0, 0, result.getWidth(), result.getHeight()); g2.setColor(Color.black); g2.setFont(Font.decode("\"Arial\", Font.BOLD, 12")); int offset = 0; int count = 0; for (Iterator<BufferedImage> iterator = results.iterator(); iterator.hasNext();) { BufferedImage next = iterator.next(); g2.drawImage(next, offset, 20, null); g2.drawString(hits.score(count) + "", offset + 5, 12); offset += next.getWidth() + 5; count++; } ImageIO.write(result, "PNG", new File(prefix + "_" + (System.currentTimeMillis() / 1000) + ".png")); }
From source file:org.osmdroid.geopackagetoosm.Main.java
/** * Write GeoPackage formatted tiles//from w ww.j a va 2s .c om * * @param tileDao * @param zoomLevel * @param tileMatrix * @param zDirectory * @param imageFormat * @param rawImage * @return * @throws IOException */ private static int writeGeoPackageFormatTiles(TileDao tileDao, long zoomLevel, TileMatrix tileMatrix, File zDirectory, String imageFormat, boolean rawImage) throws IOException { int tileCount = 0; // Go through each x in the width for (int x = 0; x < tileMatrix.getMatrixWidth(); x++) { File xDirectory = new File(zDirectory, String.valueOf(x)); // Go through each y in the height for (int y = 0; y < tileMatrix.getMatrixHeight(); y++) { // Query for a tile at the x, y, z TileRow tileRow = tileDao.queryForTile(x, y, zoomLevel); if (tileRow != null) { // Get the image bytes byte[] tileData = tileRow.getTileData(); if (tileData != null) { // Make any needed directories for the image xDirectory.mkdirs(); File imageFile = new File(xDirectory, String.valueOf(y) + "." + imageFormat); if (rawImage) { // Write the raw image bytes to the file FileOutputStream fos = new FileOutputStream(imageFile); fos.write(tileData); fos.close(); } else { // Read the tile image BufferedImage tileImage = tileRow.getTileDataImage(); // Create the new image in the image format BufferedImage image = ImageUtils.createBufferedImage(tileImage.getWidth(), tileImage.getHeight(), imageFormat); Graphics graphics = image.getGraphics(); // Draw the image graphics.drawImage(tileImage, 0, 0, null); // Write the image to the file ImageIO.write(image, imageFormat, imageFile); } tileCount++; if (tileCount % ZOOM_PROGRESS_FREQUENCY == 0) { LOGGER.log(Level.INFO, "Zoom " + zoomLevel + " Tile Progress... " + tileCount); } } } } } return tileCount; }
From source file:org.apache.ofbiz.common.CommonEvents.java
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) { try {// ww w.j av a2 s .c o m Delegator delegator = (Delegator) request.getAttribute("delegator"); final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default"); final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "captcha." + captchaSizeConfigName, delegator); final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|"); final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored final int fontSize = Integer.parseInt(captchaSizeConfigs[0]); final int height = Integer.parseInt(captchaSizeConfigs[1]); final int width = Integer.parseInt(captchaSizeConfigs[2]); final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6); final char[] availableChars = EntityUtilProperties .getPropertyValue("captcha", "captcha.characters", delegator).toCharArray(); //It is possible to pass the font size, image width and height with the request as well Color backgroundColor = Color.gray; Color borderColor = Color.DARK_GRAY; Color textColor = Color.ORANGE; Color circleColor = new Color(160, 160, 160); Font textFont = new Font("Arial", Font.PLAIN, fontSize); int circlesToDraw = 6; float horizMargin = 20.0f; double rotationRange = 0.7; // in radians BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setColor(backgroundColor); g.fillRect(0, 0, width, height); //Generating some circles for background noise g.setColor(circleColor); for (int i = 0; i < circlesToDraw; i++) { int circleRadius = (int) (Math.random() * height / 2.0); int circleX = (int) (Math.random() * width - circleRadius); int circleY = (int) (Math.random() * height - circleRadius); g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2); } g.setColor(textColor); g.setFont(textFont); FontMetrics fontMetrics = g.getFontMetrics(); int maxAdvance = fontMetrics.getMaxAdvance(); int fontHeight = fontMetrics.getHeight(); String captchaCode = RandomStringUtils.random(6, availableChars); float spaceForLetters = -horizMargin * 2 + width; float spacePerChar = spaceForLetters / (charsToPrint - 1.0f); for (int i = 0; i < captchaCode.length(); i++) { // this is a separate canvas used for the character so that // we can rotate it independently int charWidth = fontMetrics.charWidth(captchaCode.charAt(i)); int charDim = Math.max(maxAdvance, fontHeight); int halfCharDim = (charDim / 2); BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB); Graphics2D charGraphics = charImage.createGraphics(); charGraphics.translate(halfCharDim, halfCharDim); double angle = (Math.random() - 0.5) * rotationRange; charGraphics.transform(AffineTransform.getRotateInstance(angle)); charGraphics.translate(-halfCharDim, -halfCharDim); charGraphics.setColor(textColor); charGraphics.setFont(textFont); int charX = (int) (0.5 * charDim - 0.5 * charWidth); charGraphics.drawString("" + captchaCode.charAt(i), charX, ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent())); float x = horizMargin + spacePerChar * (i) - charDim / 2.0f; int y = ((height - charDim) / 2); g.drawImage(charImage, (int) x, y, charDim, charDim, null, null); charGraphics.dispose(); } // Drawing the image border g.setColor(borderColor); g.drawRect(0, 0, width - 1, height - 1); g.dispose(); response.setContentType("image/jpeg"); ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); HttpSession session = request.getSession(); Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_")); if (captchaCodeMap == null) { captchaCodeMap = new HashMap<String, String>(); session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap); } captchaCodeMap.put(captchaCodeId, captchaCode); } catch (Exception ioe) { Debug.logError(ioe.getMessage(), module); } return "success"; }
From source file:Main.java
/** * Takes a snapshot of the target component. * * @param component the component to draw * @param usePrint whether <tt>print()</tt> or <tt>paint()</tt> is used to grab the snapshot * @return a Graphics compatible image of the component *///from w w w . java 2s .co m public static Image takeSnapshot(Component component, boolean usePrint) { BufferedImage image = null; GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = genv.getDefaultScreenDevice(); GraphicsConfiguration gc = gd.getDefaultConfiguration(); if (gc.getColorModel().hasAlpha()) { image = gc.createCompatibleImage((int) component.getSize().getWidth(), (int) component.getSize().getHeight()); } else { image = new BufferedImage((int) component.getSize().getWidth(), (int) component.getSize().getHeight(), BufferedImage.TYPE_INT_ARGB); } Graphics g = image.getGraphics(); if (usePrint) { component.print(g); } else { component.paint(g); } g.dispose(); return image; }
From source file:org.ofbiz.common.CommonEvents.java
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) { try {/*from www. j a va 2 s.c o m*/ Delegator delegator = (Delegator) request.getAttribute("delegator"); final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default"); final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha.properties", "captcha." + captchaSizeConfigName, delegator); final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|"); final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored final int fontSize = Integer.parseInt(captchaSizeConfigs[0]); final int height = Integer.parseInt(captchaSizeConfigs[1]); final int width = Integer.parseInt(captchaSizeConfigs[2]); final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha.properties", "captcha.code_length", 6); final char[] availableChars = EntityUtilProperties .getPropertyValue("captcha.properties", "captcha.characters", delegator).toCharArray(); //It is possible to pass the font size, image width and height with the request as well Color backgroundColor = Color.gray; Color borderColor = Color.DARK_GRAY; Color textColor = Color.ORANGE; Color circleColor = new Color(160, 160, 160); Font textFont = new Font("Arial", Font.PLAIN, fontSize); int circlesToDraw = 6; float horizMargin = 20.0f; double rotationRange = 0.7; // in radians BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setColor(backgroundColor); g.fillRect(0, 0, width, height); //Generating some circles for background noise g.setColor(circleColor); for (int i = 0; i < circlesToDraw; i++) { int circleRadius = (int) (Math.random() * height / 2.0); int circleX = (int) (Math.random() * width - circleRadius); int circleY = (int) (Math.random() * height - circleRadius); g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2); } g.setColor(textColor); g.setFont(textFont); FontMetrics fontMetrics = g.getFontMetrics(); int maxAdvance = fontMetrics.getMaxAdvance(); int fontHeight = fontMetrics.getHeight(); String captchaCode = RandomStringUtils.random(6, availableChars); float spaceForLetters = -horizMargin * 2 + width; float spacePerChar = spaceForLetters / (charsToPrint - 1.0f); for (int i = 0; i < captchaCode.length(); i++) { // this is a separate canvas used for the character so that // we can rotate it independently int charWidth = fontMetrics.charWidth(captchaCode.charAt(i)); int charDim = Math.max(maxAdvance, fontHeight); int halfCharDim = (charDim / 2); BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB); Graphics2D charGraphics = charImage.createGraphics(); charGraphics.translate(halfCharDim, halfCharDim); double angle = (Math.random() - 0.5) * rotationRange; charGraphics.transform(AffineTransform.getRotateInstance(angle)); charGraphics.translate(-halfCharDim, -halfCharDim); charGraphics.setColor(textColor); charGraphics.setFont(textFont); int charX = (int) (0.5 * charDim - 0.5 * charWidth); charGraphics.drawString("" + captchaCode.charAt(i), charX, ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent())); float x = horizMargin + spacePerChar * (i) - charDim / 2.0f; int y = ((height - charDim) / 2); g.drawImage(charImage, (int) x, y, charDim, charDim, null, null); charGraphics.dispose(); } // Drawing the image border g.setColor(borderColor); g.drawRect(0, 0, width - 1, height - 1); g.dispose(); response.setContentType("image/jpeg"); ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); HttpSession session = request.getSession(); Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_")); if (captchaCodeMap == null) { captchaCodeMap = new HashMap<String, String>(); session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap); } captchaCodeMap.put(captchaCodeId, captchaCode); } catch (Exception ioe) { Debug.logError(ioe.getMessage(), module); } return "success"; }