How to load image in canvas using JPEGImageDecoder class in Java?

DeeKay July 18, 2011 at 11:48 pm · java.applet

/****************************************************************************************
 * Created on 07-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.image.codec;

import com.sun.image.codec.jpeg.JPEGCodec;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;

/**
 * This java code example show how to use JPEGImageDecoder class of  com.sun.image.codec.jpeg
 * package.
 * Created by http://kodehelp.com
 * Date: 7/18/11
 */
public class JPEGImageDecoder {

     public static void main(String[] args) throws Exception {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        MyCanvas tl = new MyCanvas();
        cp.add(tl);
        jf.setSize(800, 500);
        jf.setVisible(true);
    }

    static class MyCanvas extends JPanel {
        BufferedImage mImage;
        public MyCanvas() {
            try {
                InputStream in = getClass().getResourceAsStream("demo.jpg");
                com.sun.image.codec.jpeg.JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
                mImage = decoder.decodeAsBufferedImage();
                in.close();
            }catch (Exception e){
                System.err.println(e.getLocalizedMessage());
            }
            ImageIcon icon = new ImageIcon(mImage);
            add(new JLabel(icon));
        }
    }
}