List of usage examples for java.awt Graphics2D setRenderingHint
public abstract void setRenderingHint(Key hintKey, Object hintValue);
From source file:z.tool.util.image.ImageUtil.java
/** * //from w ww . j a va2 s .c om */ public static void resize(InputStream inputStream, ImageType destType, OutputStream outputStream, int maxNewWidth, int maxNewHeight) { if (null == inputStream) { throw new IllegalArgumentException("inputStream is null"); } if (null == destType) { throw new IllegalArgumentException("destType is null"); } if (null == outputStream) { throw new IllegalArgumentException("outputStream is null"); } try { Image srcImage = ImageIO.read(inputStream); // ? int srcImageWidth = srcImage.getWidth(null); int srcImageHeight = srcImage.getHeight(null); if (0 == maxNewWidth || 0 == maxNewHeight || (srcImageWidth <= maxNewWidth && srcImageHeight <= maxNewHeight)) { maxNewWidth = srcImageWidth; maxNewHeight = srcImageHeight; } else { // // ? if (srcImageWidth >= srcImageHeight) { // ??? maxNewHeight = (int) Math.round((srcImageHeight * maxNewWidth * 1.0 / srcImageWidth)); } else { // ??? maxNewWidth = (int) Math.round((srcImageWidth * maxNewHeight * 1.0 / srcImageHeight)); } } BufferedImage distImage = new BufferedImage(maxNewWidth, maxNewHeight, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D graphics2d = distImage.createGraphics(); graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // graphics2d.drawImage(srcImage.getScaledInstance(maxNewWidth, maxNewHeight, Image.SCALE_SMOOTH), 0, 0, null); // ? ImageIO.write(distImage, destType.name(), outputStream); } catch (IOException e) { LOG.error("method:resize,destType:" + destType + ",maxNewHeight:" + maxNewHeight + ",maxNewWidth:" + maxNewWidth + ",errorMsg:" + e.getMessage(), e); throw new HumanNeededError(Error.IO_ERROR); } }
From source file:com.sun.socialsite.util.ImageUtil.java
/** * Convenience method that returns a scaled instance of the * provided {@code BufferedImage}./*w w w .j a v a2 s. co m*/ * * NOTE: Adapted from code at * {@link http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html}. * * @param img the original image to be scaled * @param targetWidth the desired width of the scaled instance, * in pixels * @param targetHeight the desired height of the scaled instance, * in pixels * @param hint one of the rendering hints that corresponds to * {@code RenderingHints.KEY_INTERPOLATION} (e.g. * {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, * {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, * {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) * @param higherQuality if true, this method will use a multi-step * scaling technique that provides higher quality than the usual * one-step technique (only useful in downscaling cases, where * {@code targetWidth} or {@code targetHeight} is * smaller than the original dimensions, and generally only when * the {@code BILINEAR} hint is specified) * @return a scaled version of the original {@code BufferedImage} */ private static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint, boolean higherQuality) { int type = BufferedImage.TYPE_INT_ARGB; BufferedImage ret = (BufferedImage) img; int w, h; if (higherQuality) { // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); h = img.getHeight(); } else { // Use one-step technique: scale directly from original // size to target size with a single drawImage() call w = targetWidth; h = targetHeight; } do { if (higherQuality && w > targetWidth) { w /= 2; if (w < targetWidth) { w = targetWidth; } } if (higherQuality && h > targetHeight) { h /= 2; if (h < targetHeight) { h = targetHeight; } } BufferedImage tmp = new BufferedImage(w, h, type); Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint); g2.drawImage(ret, 0, 0, w, h, null); g2.dispose(); ret = tmp; } while (w > targetWidth || h > targetHeight); return ret; }
From source file:z.tool.util.image.ImageUtil.java
/** * ??(???)//from w w w. j ava2s .c o m */ public static void mergeResource(int bufferedImageType, InputStream inputStream, ImageType destType, OutputStream outputStream, int newHeight, int newWidth, Mergeable mergeable, Mergeable... mergeables) { if (null == inputStream) { throw new IllegalArgumentException("inputStream is null"); } if (null == destType) { throw new IllegalArgumentException("destType is null"); } if (null == outputStream) { throw new IllegalArgumentException("outputStream is null"); } try { Image srcImage = ImageIO.read(inputStream); // ? int srcImageWidth = srcImage.getWidth(null); int srcImageHeight = srcImage.getHeight(null); // ???? if (0 == newWidth || 0 == newHeight) { newWidth = srcImageWidth; newHeight = srcImageHeight; } BufferedImage distImage = new BufferedImage(newWidth, newHeight, bufferedImageType); // Graphics2D graphics2d = distImage.createGraphics(); graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); graphics2d.drawImage(srcImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); // ??(?) mergeable.draw(graphics2d); // ??(?) if (null != mergeables && mergeables.length > 0) { for (Mergeable d : mergeables) { d.draw(graphics2d); } } // ? ImageIO.write(distImage, destType.name(), outputStream); } catch (IOException e) { LOG.error("method:mergeResource,destType:" + destType + ",newHeight:" + newHeight + ",newWidth:" + newWidth + ",errorMsg:" + e.getMessage(), e); throw new HumanNeededError(Error.IO_ERROR); } }
From source file:FileUtils.java
/** * Convenience method that returns a scaled instance of the * provided {@code BufferedImage}./* www . ja va 2 s . c om*/ * * @param img the original image to be scaled * @param targetWidth the desired width of the scaled instance, * in pixels * @param targetHeight the desired height of the scaled instance, * in pixels * @param hint one of the rendering hints that corresponds to * {@code RenderingHints.KEY_INTERPOLATION} (e.g. * {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, * {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, * {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) * @param higherQuality if true, this method will use a multi-step * scaling technique that provides higher quality than the usual * one-step technique (only useful in downscaling cases, where * {@code targetWidth} or {@code targetHeight} is * smaller than the original dimensions, and generally only when * the {@code BILINEAR} hint is specified) * @return a scaled version of the original {@code BufferedImage} */ public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint, boolean higherQuality) { final int type = img.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage ret = (BufferedImage) img; int w; int h; if (higherQuality) { // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); h = img.getHeight(); } else { // Use one-step technique: scale directly from original // size to target size with a single drawImage() call w = targetWidth; h = targetHeight; } do { if (higherQuality && w > targetWidth) { w /= 2; if (w < targetWidth) { w = targetWidth; } } if (higherQuality && h > targetHeight) { h /= 2; if (h < targetHeight) { h = targetHeight; } } final BufferedImage tmp = new BufferedImage(w, h, type); final Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint); g2.drawImage(ret, 0, 0, w, h, null); g2.dispose(); ret = tmp; } while (w != targetWidth || h != targetHeight); return ret; }
From source file:game.com.HandleUploadGameThumbServlet.java
public static BufferedImage resizeImage(final Image image, int width, int height) { final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); final Graphics2D graphics2D = bufferedImage.createGraphics(); graphics2D.setComposite(AlphaComposite.Src); //below three lines are for RenderingHints for better image quality at cost of higher processing time graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.drawImage(image, 0, 0, width, height, null); graphics2D.dispose();/*w w w . j a va 2 s . c o m*/ return bufferedImage; }
From source file:org.deeplearning4j.examples.multigpu.video.VideoGenerator.java
private static int[] generateVideo(String path, int nFrames, int width, int height, int numShapes, Random r, boolean backgroundNoise, int numDistractorsPerFrame) throws Exception { //First: decide where transitions between one shape and another are double[] rns = new double[numShapes]; double sum = 0; for (int i = 0; i < numShapes; i++) { rns[i] = r.nextDouble();//from w w w. j a v a2s . co m sum += rns[i]; } for (int i = 0; i < numShapes; i++) rns[i] /= sum; int[] startFrames = new int[numShapes]; startFrames[0] = 0; for (int i = 1; i < numShapes; i++) { startFrames[i] = (int) (startFrames[i - 1] + MIN_FRAMES + rns[i] * (nFrames - numShapes * MIN_FRAMES)); } //Randomly generate shape positions, velocities, colors, and type int[] shapeTypes = new int[numShapes]; int[] initialX = new int[numShapes]; int[] initialY = new int[numShapes]; double[] velocityX = new double[numShapes]; double[] velocityY = new double[numShapes]; Color[] color = new Color[numShapes]; for (int i = 0; i < numShapes; i++) { shapeTypes[i] = r.nextInt(NUM_SHAPES); initialX[i] = SHAPE_MIN_DIST_FROM_EDGE + r.nextInt(width - SHAPE_SIZE - 2 * SHAPE_MIN_DIST_FROM_EDGE); initialY[i] = SHAPE_MIN_DIST_FROM_EDGE + r.nextInt(height - SHAPE_SIZE - 2 * SHAPE_MIN_DIST_FROM_EDGE); velocityX[i] = -1 + 2 * r.nextDouble(); velocityY[i] = -1 + 2 * r.nextDouble(); color[i] = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat()); } //Generate a sequence of BufferedImages with the given shapes, and write them to the video SequenceEncoder enc = new SequenceEncoder(new File(path)); int currShape = 0; int[] labels = new int[nFrames]; for (int i = 0; i < nFrames; i++) { if (currShape < numShapes - 1 && i >= startFrames[currShape + 1]) currShape++; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bi.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setBackground(Color.BLACK); if (backgroundNoise) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bi.setRGB(x, y, new Color(r.nextFloat() * MAX_NOISE_VALUE, r.nextFloat() * MAX_NOISE_VALUE, r.nextFloat() * MAX_NOISE_VALUE).getRGB()); } } } g2d.setColor(color[currShape]); //Position of shape this frame int currX = (int) (initialX[currShape] + (i - startFrames[currShape]) * velocityX[currShape] * MAX_VELOCITY); int currY = (int) (initialY[currShape] + (i - startFrames[currShape]) * velocityY[currShape] * MAX_VELOCITY); //Render the shape switch (shapeTypes[currShape]) { case 0: //Circle g2d.fill(new Ellipse2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE)); break; case 1: //Square g2d.fill(new Rectangle2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE)); break; case 2: //Arc g2d.fill(new Arc2D.Double(currX, currY, SHAPE_SIZE, SHAPE_SIZE, 315, 225, Arc2D.PIE)); break; case 3: //Line g2d.setStroke(lineStroke); g2d.draw(new Line2D.Double(currX, currY, currX + SHAPE_SIZE, currY + SHAPE_SIZE)); break; default: throw new RuntimeException(); } //Add some distractor shapes, which are present for one frame only for (int j = 0; j < numDistractorsPerFrame; j++) { int distractorShapeIdx = r.nextInt(NUM_SHAPES); int distractorX = DISTRACTOR_MIN_DIST_FROM_EDGE + r.nextInt(width - SHAPE_SIZE); int distractorY = DISTRACTOR_MIN_DIST_FROM_EDGE + r.nextInt(height - SHAPE_SIZE); g2d.setColor(new Color(r.nextFloat(), r.nextFloat(), r.nextFloat())); switch (distractorShapeIdx) { case 0: g2d.fill(new Ellipse2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE)); break; case 1: g2d.fill(new Rectangle2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE)); break; case 2: g2d.fill(new Arc2D.Double(distractorX, distractorY, SHAPE_SIZE, SHAPE_SIZE, 315, 225, Arc2D.PIE)); break; case 3: g2d.setStroke(lineStroke); g2d.draw(new Line2D.Double(distractorX, distractorY, distractorX + SHAPE_SIZE, distractorY + SHAPE_SIZE)); break; default: throw new RuntimeException(); } } enc.encodeImage(bi); g2d.dispose(); labels[i] = shapeTypes[currShape]; } enc.finish(); //write .mp4 return labels; }
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; }//ww w . ja va 2s . c om 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:com.partagames.imageresizetool.SimpleImageResizeTool.java
/** * Scales an image to the desired dimensions. * * @param img Original image/*w w w . ja va 2s. c o m*/ * @param newW Target width * @param newH Target height * @return Scaled image */ public static BufferedImage scale(BufferedImage img, int newW, int newH) { int w = img.getWidth(); int h = img.getHeight(); final BufferedImage dimg = new BufferedImage(newW, newH, img.getType()); final Graphics2D g = dimg.createGraphics(); // use provided rendering hint, default is bilinear switch (scalingHint) { case "n": g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); break; case "b": g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); break; } g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null); g.dispose(); return dimg; }
From source file:Main.java
/** * Creates and returns image from the given text. * @param text input text/*from w w w. j av a 2s. c om*/ * @param font text font * @return image with input text */ public static BufferedImage createImageFromText(String text, Font font) { //You may want to change these setting, or make them parameters boolean isAntiAliased = true; boolean usesFractionalMetrics = false; FontRenderContext frc = new FontRenderContext(null, isAntiAliased, usesFractionalMetrics); TextLayout layout = new TextLayout(text, font, frc); Rectangle2D bounds = layout.getBounds(); int w = (int) Math.ceil(bounds.getWidth()); int h = (int) Math.ceil(bounds.getHeight()) + 2; BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); //for example; Graphics2D g = image.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, w, h); g.setColor(Color.BLACK); g.setFont(font); Object antiAliased = isAntiAliased ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF; g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, antiAliased); Object fractionalMetrics = usesFractionalMetrics ? RenderingHints.VALUE_FRACTIONALMETRICS_ON : RenderingHints.VALUE_FRACTIONALMETRICS_OFF; g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, fractionalMetrics); g.drawString(text, (float) -bounds.getX(), (float) -bounds.getY()); g.dispose(); return image; }
From source file:kz.supershiny.core.services.ImageService.java
/** * Creates thumb for image./*from w w w . j a va 2 s . c o m*/ * * @param originalData original image in byte array * @param type original - 0, large - 1, small - 2 * @return resized image in byte array */ public static byte[] resizeImage(byte[] originalData, ImageSize type) { //if original flag, then return original if (type.equals(ImageSize.ORIGINAL)) { return originalData; } BufferedImage originalImage = null; BufferedImage resizedImage = null; byte[] result = null; //convert bytes to BufferedImage try (InputStream in = new ByteArrayInputStream(originalData)) { originalImage = ImageIO.read(in); } catch (IOException ex) { LOG.error("Cannot convert byte array to BufferedImage!", ex); return null; } //get original size int scaledHeight = originalImage.getHeight(); int scaledWidth = originalImage.getWidth(); switch (type) { case LARGE: scaledWidth = LARGE_WIDTH; scaledHeight = LARGE_HEIGHT; break; case SMALL: scaledWidth = SMALL_WIDTH; scaledHeight = SMALL_HEIGHT; break; default: break; } //calculate aspect ratio float ratio = 1.0F * originalImage.getWidth() / originalImage.getHeight(); if (ratio > 1.0F) { scaledHeight = (int) (scaledHeight / ratio); } else { scaledWidth = (int) (scaledWidth * ratio); } //resize with hints resizedImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType()); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); g.dispose(); g.setComposite(AlphaComposite.Src); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //convert BufferedImage to bytes try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write(resizedImage, "png", baos); baos.flush(); result = baos.toByteArray(); } catch (IOException ex) { LOG.error("Cannot convert BufferedImage to byte array!", ex); } return result; }