Java Tutorial/2D Graphics/JPEG — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 15:24, 31 мая 2010

Encoding an image to a JPEG file

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.FileOutputStream;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Main {
  public static void main(String[] args) throws Exception {
    BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    Graphics g = img.getGraphics();
    g.setColor(Color.red);
    g.setFont(new Font("Arial", Font.BOLD, 14));
    g.drawString("Reference", 10, 80);
    int w = 100;
    int h = 100;
    int x = 1;
    int y = 1;
    
    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
    pg.grabPixels();
    BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    for (int j = 0; j < h; j++) {
      for (int i = 0; i < w; i++) {
        bimg.setRGB(x + i, y + j, pixels[j * w + i]);
      }
    }
    FileOutputStream fout = new FileOutputStream("jpg.jpg");
    JPEGImageEncoder jencoder = JPEGCodec.createJPEGEncoder(fout);
    JPEGEncodeParam enParam = jencoder.getDefaultJPEGEncodeParam(bimg);
    enParam.setQuality(1.0F, true);
    jencoder.setJPEGEncodeParam(enParam);
    jencoder.encode(bimg);
    fout.close();
  }
}





Rescale JPG

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Main {
  public static void main(String[] args) throws Exception {
    BufferedImage bsrc = ImageIO.read(new File("a.jpg"));
    BufferedImage bdest = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bdest.createGraphics();
    AffineTransform at = AffineTransform.getScaleInstance(2, 2);
    g.drawRenderedImage(bsrc, at);
    ImageIO.write(bdest, "JPG", new File("b.jpg"));
  }
}