/** * Adds next GIF frame. The frame is not written immediately, but is actually deferred until the * next frame is received so that timing data can be inserted. Invoking <code>finish()</code> * flushes all frames. If <code>setSize</code> was not invoked, the size of the first image is * used for all subsequent frames. * * @param im BufferedImage containing frame to write. * @throws IOException if there was an IOException writing the GIF data * @throws IllegalArgumentException if this encoder has not been started */ public void addFrame(BufferedImage im) throws IOException { if (!started) { throw new IllegalStateException("AnimatedGifEncoder not started"); } if (!sizeSet) { // use first frame's size setSize(im.getWidth(), im.getHeight()); } image = im; getImagePixels(); // convert to correct format if necessary analyzePixels(); // build color table & map pixels if (firstFrame) { writeLSD(); // logical screen descriptior writePalette(); // global color table if (repeat >= 0) { // use NS app extension to indicate reps writeNetscapeExt(); } } writeGraphicCtrlExt(); // write graphic control extension writeImageDesc(); // image descriptor if (!firstFrame) { writePalette(); // local color table } writePixels(); // encode and write pixel data firstFrame = false; }
/** * Returns the specified image as icon. * * @param name name of icon * @return icon */ public static ImageIcon icon(final String name) { ImageIcon ii = ICONS.get(name); if (ii != null) return ii; Image img; if (GUIConstants.scale > 1) { // choose large image or none final URL url = GUIConstants.large() ? BaseXImages.class.getResource("/img/" + name + "_32.png") : null; if (url == null) { // resize low-res image if no hi-res image exists img = get(url(name)); final int w = (int) (img.getWidth(null) * GUIConstants.scale); final int h = (int) (img.getHeight(null) * GUIConstants.scale); final BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.drawImage(img, 0, 0, w, h, null); g2.dispose(); img = tmp; } else { img = get(url); } } else { img = get(name); } ii = new ImageIcon(img); ICONS.put(name, ii); return ii; }
/** * Convert a source to a BufferedImage. Source supported: * File,BufferedImage,InputStream,URL,ImageInputStream, byte[] * * @param imageType the ImageType to use * @param source source to generate BufferedImage from * @return Enhanced BufferedImage * @throws NullPointerException _ * @throws IOException _ * @throws UnsupportedOperationException throws this is the source is of unsupported type */ public static <T> BufferedImage convertImageType(final ImageType imageType, final T source) throws NullPointerException, IOException, UnsupportedOperationException { if (verifyNotNull(imageType, source)) { BufferedImage target = null; if (source instanceof File) { target = convert(ImageIO.read((File) source), imageType); } else if (source instanceof BufferedImage) { target = convert((BufferedImage) source, imageType); } else if (source instanceof InputStream) { target = convert(ImageIO.read((InputStream) source), imageType); } else if (source instanceof URL) { target = convert(ImageIO.read((URL) source), imageType); } else if (source instanceof ImageInputStream) { target = convert(ImageIO.read((ImageInputStream) source), imageType); } else if (source instanceof byte[]) { final InputStream streamOfInput = new ByteArrayInputStream((byte[]) source); target = convert(ImageIO.read(streamOfInput), imageType); } else { throw new UnsupportedOperationException("%s is not supported. Read JavaDoc."); } if (verifyNotNull(target)) { LOGGER.info( String.format( "Returning requested converted object<%s> as target", target.getClass().getName())); return target; } throw new NullPointerException("Return value was null."); } throw new NullPointerException("Nilled param detected. Please verify your params!"); }
public static BufferedImage encodeImage(String filename, int[] primes) { /* encodes a and b in the image using a sequence. * We are assuming that the image would be big enough * to hold the 16 bits */ BufferedImage img, newimg = null; int[] a = convertToBinary(primes[0], 8); int[] b = convertToBinary(primes[1], 8); int[] a_b = copyBits(a, b); // copy all bits into one array try { img = ImageIO.read(new File(imagePath + filename)); for (int i = 0; i < a_b.length; i++) { int p = img.getRGB(i, i); int[] bin = convertToBinary(p, 32); bin[0] = a_b[i]; int d = convertToDigit(bin, 32); img.setRGB(i, i, d); } ImageIO.write(img, "png", new File(imagePath + "new_" + filename)); newimg = ImageIO.read(new File(imagePath + "new_" + filename)); } catch (IOException e) { System.out.println("ERROR WRITING IMAGE...\n" + e.toString()); System.exit(1); } return newimg; }
/** * Save onscreen image to file - suffix must be png, jpg, or gif. * * @param filename the name of the file with one of the required suffixes */ public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: // http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel( cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } }
private void gameRender() { if (dbImage == null) { dbImage = createImage(PWIDTH, PHEIGHT); if (dbImage == null) { System.out.println("dbImage is null"); return; } else dbg = dbImage.getGraphics(); } // draw a white background dbg.setColor(Color.white); dbg.fillRect(0, 0, PWIDTH, PHEIGHT); // draw the game elements: order is important ribsMan.display(dbg); // the background ribbons bricksMan.display(dbg); // the bricks jack.drawSprite(dbg); // the sprites fireball.drawSprite(dbg); if (showExplosion) // draw the explosion (in front of jack) dbg.drawImage(explosionPlayer.getCurrentImage(), xExpl, yExpl, null); reportStats(dbg); if (gameOver) gameOverMessage(dbg); if (showHelp) // draw the help at the very front (if switched on) dbg.drawImage( helpIm, (PWIDTH - helpIm.getWidth()) / 2, (PHEIGHT - helpIm.getHeight()) / 2, null); } // end of gameRender()
/** * Appends a frame to the current video. * * @param image the image to append * @return true if image successfully appended */ protected boolean append(Image image) { BufferedImage bi; if (image instanceof BufferedImage) { bi = (BufferedImage) image; } else { bi = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.drawImage(image, 0, 0, null); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { if (!editing) { videoMedia.beginEdits(); editing = true; } ImageIO.write(bi, "png", out); // $NON-NLS-1$ QTHandle handle = new QTHandle(out.toByteArray()); DataRef dataRef = new DataRef(handle, kDataRefFileExtensionTag, "png"); // $NON-NLS-1$ GraphicsImporter importer = new GraphicsImporter(dataRef); ImageDescription description = importer.getImageDescription(); int duration = (int) (frameDuration * 0.6); videoMedia.addSample( handle, 0, // data offset handle.getSize(), duration, description, 1, // number of samples 0); // key frame?? } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
private void stuffWithLeastSignificantBit(BufferedImage image, byte[] message) { int[] pixelValues = getImagePixels(image); if (message.length * 8 > pixelValues.length * 3) { System.out.printf("Cannot stuff message in least significant bit\n"); } int messageIndex = 0; int currentByteOffset = -1; pixls: for (int i = 0; i < pixelValues.length; i++) { for (int offset = 0; offset < 17; offset += 8) { currentByteOffset++; if (currentByteOffset > 7) { currentByteOffset = 0; messageIndex++; } if (messageIndex >= message.length) break pixls; int bitToEncode = (message[messageIndex] >> currentByteOffset) & 1; // color = (byte) ((color & 0xfe) | bitToEncode); // zero pixelValues[i] &= ~(0x1 << offset); // fill pixelValues[i] |= bitToEncode << offset; } } // put pixel ints back into BufferedImage for (int i = 0; i < pixelValues.length; i++) { int x = i % image.getWidth(); int y = i / image.getWidth(); image.setRGB(x, y, pixelValues[i]); } }
public BufferedImage filter(BufferedImage src, BufferedImage dst) { icentreX = src.getWidth() * centreX; icentreY = src.getHeight() * centreY; if (radius == 0) radius = Math.min(icentreX, icentreY); radius2 = radius * radius; return super.filter(src, dst); }
public SimpleWhiteboardPanel(int width, int height) { this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = this.image.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, image.getWidth(), image.getHeight()); this.setFocusable(true); }
/** Creates a new instance of IDEJRManFramebufferImpl */ public IDEJRManFramebufferImpl(String name, BufferedImage image) { super("JRMan rendered: " + name, true, true, true, true); this.name = name; save.setEnabled(false); imagePanel.setImage(image); imagePanel.addToolbarAction(save); if (image.getType() == BufferedImage.TYPE_INT_ARGB || image.getType() == BufferedImage.TYPE_INT_ARGB_PRE) { imagePanel.setShowTransparencyPattern(true); } getRootPane().setDoubleBuffered(false); getContentPane().add(imagePanel); pack(); ImageResource images = ImageResource.getInstance(); // set the frame icon setFrameIcon(images.getJrMan()); // add this to the IDE desktop MainMenuEventHandlers.getInstance(null) .getIdeInstance() .getWorkspaceDesktop() .addInternalFrame(this, true); }
// This is used to create a CImage from a Image public CImage createFromImage(final Image image) { if (image == null) return null; MediaTracker mt = new MediaTracker(new Label()); final int id = 0; mt.addImage(image, id); try { mt.waitForID(id); } catch (InterruptedException e) { } if (mt.isErrorID(id)) { return null; } int w = image.getWidth(null); int h = image.getHeight(null); BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = bimg.createGraphics(); g2.setComposite(AlphaComposite.Src); g2.drawImage(image, 0, 0, null); g2.dispose(); int[] buffer = ((DataBufferInt) bimg.getRaster().getDataBuffer()).getData(); return new CImage(nativeCreateNSImageFromArray(buffer, w, h)); }
public void generarFondo(Component componente) { boolean dibujarFondo = false; Rectangle med = this.getBounds(); Rectangle areaDibujo = this.getBounds(); BufferedImage tmp; GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); if (Principal.fondoBlur) { dibujarFondo = true; } if (dibujarFondo) { JRootPane root = SwingUtilities.getRootPane(this); blurBuffer = GraphicsUtilities.createCompatibleImage(Principal.sysAncho, Principal.sysAlto); Graphics2D g2 = blurBuffer.createGraphics(); g2.setClip(med); blurBuffer = blurBuffer.getSubimage(med.x, med.y, med.width, med.height); ((Escritorio) Principal.getEscritorio()).getFrameEscritorio().paint(g2); g2.dispose(); backBuffer = blurBuffer; // blurBuffer = toGrayScale(blurBuffer); blurBuffer = GraphicsUtilities.createThumbnailFast(blurBuffer, getWidth() / 2); blurBuffer = new GaussianBlurFilter(4).filter(blurBuffer, null); g2 = (Graphics2D) blurBuffer.getGraphics(); g2.setColor(new Color(0, 0, 0, 195)); g2.fillRect(0, 0, Principal.sysAncho, Principal.sysAlto); listo = true; } }
public static void saveJPG(Image img, String s) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, null, null); FileOutputStream out = null; try { out = new FileOutputStream(s); } catch (java.io.FileNotFoundException io) { System.out.println("File Not Found"); } JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi); param.setQuality(0.5f, false); encoder.setJPEGEncodeParam(param); try { encoder.encode(bi); out.close(); } catch (java.io.IOException io) { System.out.println("IOException"); } }
public void scaleImage( Image image, int p_width, int p_height, boolean keepaspect) /*throws Exception*/ { int thumbWidth = p_width; int thumbHeight = p_height; // Make sure the aspect ratio is maintained, so the image is not skewed if (keepaspect) { double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); this.img = thumbImage; }
public void draw(BufferedImage buf) { WritableRaster dst = buf.getRaster(); blit(dst, bg.getRaster(), Coord.z); alphablit(dst, rmeter(sbars[0].getRaster(), lmax[0], max), mc[0]); alphablit( dst, lmeter(sbars[1].getRaster(), lmax[1], max), mc[1].sub(bars[1].getWidth() - 1, 0)); alphablit( dst, lmeter(sbars[2].getRaster(), lmax[2], max), mc[2].sub(bars[2].getWidth() - 1, 0)); alphablit(dst, rmeter(sbars[3].getRaster(), lmax[3], max), mc[3]); if (lfood != null) { double e = foodeff(lfood); alphablit(dst, rgmeter(lfood, e, 0), mc[0]); alphablit(dst, lgmeter(lfood, e, 1), mc[1].sub(bars[1].getWidth() - 1, 0)); alphablit(dst, lgmeter(lfood, e, 2), mc[2].sub(bars[1].getWidth() - 1, 0)); alphablit(dst, rgmeter(lfood, e, 3), mc[3]); } alphablit(dst, rmeter(bars[0].getRaster(), lev[0], max), mc[0]); alphablit(dst, lmeter(bars[1].getRaster(), lev[1], max), mc[1].sub(bars[1].getWidth() - 1, 0)); alphablit(dst, lmeter(bars[2].getRaster(), lev[2], max), mc[2].sub(bars[2].getWidth() - 1, 0)); alphablit(dst, rmeter(bars[3].getRaster(), lev[3], max), mc[3]); StringBuilder tbuf = new StringBuilder(); for (int i = 0; i < 4; i++) tbuf.append( String.format( "%s: %s/%s\n", rnm[i], Utils.fpformat(lev[i], 3, 1), Utils.fpformat(lmax[i], 3, 1))); tooltip = RichText.render(tbuf.toString(), 0).tex(); }
public synchronized void paint(Graphics g) { if (needToStartThread) { totalDrawTime = 0; counter = 0; needToStartThread = false; startThread(beginAngle, endAngle); if (firstImage == null) { firstImage = createImageFromComponent(component1); } if (secondImage == null) { secondImage = createImageFromComponent(component2); } } if (firstImage == null || secondImage == null) return; Graphics2D g2d = (Graphics2D) g; int ww = firstImage.getWidth(); int hh = firstImage.getHeight(); { BufferedImage currImage = null; int[] currPixels = null; int w = firstImage.getWidth(); int offset = (int) (w * angle / 180); if (offset < 0) offset = 0; if (offset > w) offset = w; long beforeDraw = System.currentTimeMillis(); g2d.drawImage(firstImage, null, 0, 0); g2d.drawImage(secondImage, null, w - offset, 0); totalDrawTime += (System.currentTimeMillis() - beforeDraw); counter++; } }
protected void computeGeometry() { pictHalfWidth = Width.getInt() / 2; pictWidth = pictHalfWidth + pictHalfWidth - 1; pictHeight = Height.getInt(); xLoc = -pictHalfWidth; yLoc = -pictHeight / 2; setFramesPerCycle(pictWidth - 1); setFrameIncrement(FrameIncrement.getInt()); // System.out.println("width = " + pictWidth); // System.out.println(" x = " + xLoc); // System.out.println(" y = " + yLoc); PxlColor[] ramp = AColor.getPxlColor().sinusoidalRampTo(BColor.getPxlColor(), pictHalfWidth); // System.out.println("w=" + (4*pictHalfWidth-1) + ", h=" + pictHeight); int ibWidth = 4 * pictHalfWidth - 1; if ((imageBuffer == null) || (imageBuffer.getWidth() != ibWidth) || (imageBuffer.getHeight() != pictHeight)) { imageBuffer = new BufferedImage(ibWidth, pictHeight, BufferedImage.TYPE_INT_RGB); } Graphics g = imageBuffer.getGraphics(); for (int x = 0; x < pictHalfWidth; x++) { g.setColor(ramp[x].dev()); g.drawLine(x, 0, x, pictHeight - 1); if (x < (pictHalfWidth - 1)) g.drawLine(pictWidth - x - 1, 0, pictWidth - x - 1, pictHeight - 1); if (x > 0) g.drawLine(pictWidth + x - 1, 0, pictWidth + x - 1, pictHeight - 1); if ((x > 0) && (x < (pictHalfWidth - 1))) g.drawLine(4 * pictHalfWidth - 4 - x, 0, 4 * pictHalfWidth - 4 - x, pictHeight - 1); } g.dispose(); BitMapElement p = (BitMapElement) getDisplayElement(pictElement); p.setImage(imageBuffer); p.setLocation(xLoc, yLoc); p.setClipRect(xLoc, yLoc, pictWidth, pictHeight); }
public static void main(String[] args) { int x = 500, y = 80; DrawingKit dk = new DrawingKit("Daffodils", 800, 800); BufferedImage pict = dk.loadPicture("daffodils.jpg"); // get pixel value at location (500, 80) int encodedPixelColor = pict.getRGB(x, y); Color pixelColor = new Color(encodedPixelColor); System.out.println(pixelColor); int red = pixelColor.getRed(); int green = pixelColor.getGreen(); int blue = pixelColor.getBlue(); // change the color of the pixel to be pure red red = 255; green = 0; blue = 0; // update the pixel color in picture Color newPixelColor = new Color(red, green, blue); int newRgbvalue = newPixelColor.getRGB(); pict.setRGB(x, y, newRgbvalue); // display the approximate location of the pixel dk.drawPicture(pict, 0, 0); BasicStroke s = new BasicStroke(3); dk.setStroke(s); Ellipse2D.Float e = new Ellipse2D.Float(x - 3, y - 3, 8, 8); dk.draw(e); dk.drawString("(600, 150)", x - 3, y - 5); }
public static ArthurImage add(ArthurImage one, ArthurNumber two) { BufferedImage image = JavaImageMath.clone(one.bf); int num = two.val.intValue(); WritableRaster raster = image.getRaster(); int[] pixelArray = new int[3]; for (int y = 0; y < raster.getHeight(); y++) { for (int x = 0; x < raster.getWidth(); x++) { pixelArray = raster.getPixel(x, y, pixelArray); pixelArray[0] = pixelArray[0] + num; pixelArray[1] = pixelArray[1] + num; pixelArray[2] = pixelArray[2] + num; for (int i = 0; i < 3; i++) { if (pixelArray[i] > 255) { pixelArray[i] = 255; } } raster.setPixel(x, y, pixelArray); } } // save image String outputFn = one.filename.substring(0, one.filename.indexOf(".jpg")) + "+" + // filename can't contain the / or *characters; decide later num + counter + ".jpg"; counter++; return new ArthurImage(image, outputFn); }
public static int[] decodeImage(BufferedImage img) { /* finds the hidden values in the text file */ int[] a_b, a, b; a = new int[8]; b = new int[8]; a_b = new int[2]; int i; for (i = 0; i < a.length; i++) { int p = img.getRGB(i, i); int[] bin = convertToBinary(p, 32); a[i] = bin[0]; } for (; i < (a.length + b.length); i++) { int p = img.getRGB(i, i); int[] bin = convertToBinary(p, 32); b[i - b.length] = bin[0]; } a_b[0] = convertToDigit(a, 8); a_b[1] = convertToDigit(b, 8); return a_b; }
public static ArthurImage multiply( ArthurImage one, ArthurNumber two) { // change to ArthurNumber later double f = Math.abs(two.val); // get image BufferedImage image = JavaImageMath.clone(one.bf); // manipulate image WritableRaster raster = image.getRaster(); int width = (int) (raster.getWidth() * f); int height = (int) (raster.getHeight() * f); BufferedImage collage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = collage.createGraphics(); g2d.drawImage(image, 0, 0, width, height, null); g2d.dispose(); // save image String outputFn = one.filename.substring(0, one.filename.indexOf(".jpg")) + "X" + // filename can't contain the / or *characters; decide later f + counter + ".jpg"; counter++; return new ArthurImage(collage, outputFn); }
@Override protected void paintComponent(Graphics graphics) { // Fill in the background: Graphics2D g = (Graphics2D) graphics; Shape clip = g.getClip(); g.setColor(LightZoneSkin.Colors.NeutralGray); g.fill(clip); if (preview == null) { PlanarImage image = currentImage.get(); if (image == null) { engine.update(null, false); } else if (visibleRect != null && getHeight() > 1 && getWidth() > 1) { preview = cropScaleGrayscale(visibleRect, image); } } if (preview != null) { int dx, dy; AffineTransform transform = new AffineTransform(); if (getSize().width > preview.getWidth()) dx = (getSize().width - preview.getWidth()) / 2; else dx = 0; if (getSize().height > preview.getHeight()) dy = (getSize().height - preview.getHeight()) / 2; else dy = 0; transform.setToTranslation(dx, dy); try { g.drawRenderedImage(preview, transform); } catch (Exception e) { e.printStackTrace(); } } }
public static ArthurImage add(ArthurImage one, ArthurColor two) { BufferedImage image = JavaImageMath.clone(one.bf); double r = two.r.val; double g = two.g.val; double b = two.g.val; WritableRaster raster = image.getRaster(); int[] pixelArray = new int[3]; for (int y = 0; y < raster.getHeight(); y++) { for (int x = 0; x < raster.getWidth(); x++) { pixelArray = raster.getPixel(x, y, pixelArray); pixelArray[0] = (int) (3 * pixelArray[0] + r) / 4; pixelArray[1] = (int) (3 * pixelArray[1] + g) / 4; pixelArray[2] = (int) (3 * pixelArray[2] + b) / 4; raster.setPixel(x, y, pixelArray); } } // save image String outputFn = one.filename.substring(0, one.filename.indexOf(".jpg")) + "+" + // filename can't contain the / or *characters; decide later r + g + b + counter + ".jpg"; counter++; return new ArthurImage(image, outputFn); }
protected void drawPointLegend( VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) { if (attr.getIconImageSource() == null) return; BufferedImage icon = getImage(attr.getIconImageSource()); if (icon != null) { // icon width / height int iw = icon.getWidth(); int ih = icon.getHeight(); // draw area width / height int dw = width - margin * 2; int dh = height - margin * 2; // draw scale to fit icon inside draw area float sx = iw > dw ? (float) dw / iw : 1f; // shrink only float sy = ih > dh ? (float) dh / ih : 1f; float scale = Math.min(sx, sy); iw = (int) ((float) iw * scale); ih = (int) ((float) ih * scale); // Center image and draw int x1 = iw < dw ? margin + (dw - iw) / 2 : margin; int y1 = ih < dh ? margin + (dh - ih) / 2 : margin; g2.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(icon, x1, y1, iw, ih, null); } }
// buffered images are just better. protected static BufferedImage imageToBufferedImage(Image img) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, null, null); return bi; }
public Image getScreenshot() { BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_4BYTE_ABGR); Graphics g = image.getGraphics(); paint(g); g.dispose(); return image; }
/** * Compress the uncompressed source image stored in <code>srcImage</code> and return a buffer * containing a JPEG image. * * @param srcImage a <code>BufferedImage</code> instance containing RGB or grayscale pixels to be * compressed * @param flags the bitwise OR of one or more of {@link TJ TJ.FLAG_*} * @return a buffer containing a JPEG image. The length of this buffer will not be equal to the * size of the JPEG image. Use {@link #getCompressedSize} to obtain the size of the JPEG * image. */ public byte[] compress(BufferedImage srcImage, int flags) throws Exception { int width = srcImage.getWidth(); int height = srcImage.getHeight(); byte[] buf = new byte[TJ.bufSize(width, height, subsamp)]; compress(srcImage, buf, flags); return buf; }
private <T> T scaleImageUsingAffineTransformation(final BufferedImage bufferedImage, T target) { BufferedImage destinationImage = generateDestinationImage(); Graphics2D graphics2D = destinationImage.createGraphics(); AffineTransform transformation = AffineTransform.getScaleInstance( ((double) getQualifiedWidth() / bufferedImage.getWidth()), ((double) getQualifiedHeight() / bufferedImage.getHeight())); graphics2D.drawRenderedImage(bufferedImage, transformation); graphics2D.addRenderingHints(retrieveRenderingHints()); try { if (target instanceof File) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "File")); ImageIO.write(destinationImage, imageType.toString(), (File) target); } else if (target instanceof ImageOutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "ImageOutputStream")); ImageIO.write(destinationImage, imageType.toString(), (ImageOutputStream) target); } else if (target instanceof OutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "OutputStream")); ImageIO.write(destinationImage, imageType.toString(), (OutputStream) target); } else { target = null; } } catch (IOException e) { e.printStackTrace(); } return target; }
private static BufferedImage makeBufferedImage(Icon icon, int w, int h) { BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); icon.paintIcon(null, g, (w - icon.getIconWidth()) / 2, (h - icon.getIconWidth()) / 2); g.dispose(); return image; }