Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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();

    }
}