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

[sourcecode language=”java” toolbar=”true”]
/****************************************************************************************
* Created on 07-2011 Copyright(c) https://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 https://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));
}
}
}
[/sourcecode]

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *