0% found this document useful (0 votes)
84 views

ImageLoader Java

This Java class provides methods for loading and manipulating images. It supports loading images from files, URLs, streams and input streams using different methods including ImageIcon, ImageIO and the system toolkit. It can resize images, wait for images to load fully and apply fallback loading options if the primary method fails. It includes filters for selecting image files in file open dialogs.

Uploaded by

RituSawant
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

ImageLoader Java

This Java class provides methods for loading and manipulating images. It supports loading images from files, URLs, streams and input streams using different methods including ImageIcon, ImageIO and the system toolkit. It can resize images, wait for images to load fully and apply fallback loading options if the primary method fails. It includes filters for selecting image files in file open dialogs.

Uploaded by

RituSawant
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

ImageLoader.

java
import javax.imageio.*;
import java.awt.Image;
import java.io.*;
import java.net.URL;
import javax.imageio.stream.ImageInputStream;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.image.ImageProducer;
import javax.swing.ImageIcon;
import java.lang.reflect.*;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;
import java.util.Vector;
import java.util.Iterator;
import javax.imageio.stream.ImageOutputStream;
import java.lang.Object;
public class ImageLoader {
private Component c;
private ImageFileFilter iff = null;
private ImageFileChooserFilter ifcf = null;
private int loadType=0;
private boolean fallback=true;
private int fallbackType=1;
private Class ijOpener=null;
private Object ijOpen = null;
private Class imagePlus=null;
private Method ijOpener_openImage=null;
private Method ijOpener_openURL=null;
private Method imagePlus_getImage=null;
private boolean imagejOk=false;
public static final int LOAD_IMAGEICON = 0;
public static final int LOAD_IMAGEI0 = 1;
public static final int LOAD_TOOLKIT = 3;
public static final int SCALE_SMOOTH_ENLARGER = -1;
private static final String[] imageiconTypes= {"gif","jpg","jpeg","png"};
private static final String[] toolkitTypes= {"gif","jpg","jpeg","png"};
private static String[] imagejTypes= new String[0];
public ImageLoader(Component component) {
c=component;
new ImageIcon();
ImageIO.setUseCache(false);
ImageIO.scanForPlugins();
c.getToolkit();
}
public int getLoadType(){
return loadType;
}
public void setFallbackEnabled(boolean fb){
fallback=fb;
}
public boolean setFallbackEnabled(){
return fallback;
}
public boolean isFallbackEnabled(){
return fallback;
}
public void setFallbackType(int Fallbacktype){
fallbackType=Fallbacktype;
}

public int getFallbackType(){


return fallbackType;
}
public String getSupportedTypes() {
String types = "";
String[] alltypes = getSupportedTypesArray();
for (int i = 0; i < alltypes.length; i++) {
if (i > 0) {
types += " ";
}
types += alltypes[i];
}
return types;
}
public String[] getSupportedTypesArray() {
String[] filetypes=null;
switch(loadType){
case LOAD_IMAGEICON:{
filetypes = imageiconTypes;
break;
}
case LOAD_IMAGEI0:{
filetypes = ImageIO.getReaderFormatNames();
break;
}
case LOAD_TOOLKIT:{
filetypes = toolkitTypes;
break;
}
default:{
filetypes = new String[0];
break;
}
}
return filetypes;
}
public String[] getSupportedTypesArray(int type) {
String[] filetypes=null;
switch(type){
case LOAD_IMAGEICON:{
filetypes = imageiconTypes;
break;
}
case LOAD_IMAGEI0:{
filetypes = ImageIO.getReaderFormatNames();
break;
}
case LOAD_TOOLKIT:{
filetypes = toolkitTypes;
break;
}
default:{
filetypes = new String[0];
break;
}
}
return filetypes;
}
public String getSupportedTypesSearchString() {
String types = "";

String[] alltypes = ImageIO.getReaderFormatNames();


for (int i = 0; i < alltypes.length; i++) {
if (i > 0) {
types += ", ";
}
types += "*."+alltypes[i];
}
return types;
}
public Image loadImage(File filename){
Image img=null;
try{
switch (loadType) {
case LOAD_IMAGEICON: {
img = LoadImageByImageIcon(filename);
break;
}
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(filename);
break;
}
case LOAD_TOOLKIT: {
img = LoadImageByToolkit(filename);
break;
}
}
}catch(Exception e){
System.out.println("Exception "+e+" while attempting to load image
"+filename.getAbsolutePath()+"\n Attempting to use fallback loading");
}
if((null == img || img.getWidth(null) == -1) && fallback){
switch(fallbackType){
case LOAD_IMAGEICON: {
img = LoadImageByImageIcon(filename);
break;
}
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(filename);
break;
}
case LOAD_TOOLKIT: {
img = LoadImageByToolkit(filename);
break;
}
}
}
waitForImage(img);
if(img!=null && (img instanceof java.awt.image.BufferedImage || img instanceof
java.awt.image.VolatileImage)){
img=tryToMakeAnAutomaticImage(img);
}
return img;
}
public Image loadImage(URL url){
Image img = null;
try{
switch (loadType) {
case LOAD_IMAGEICON: {
img = LoadImageByImageIcon(url);
break;

}
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(url);
break;
}
case LOAD_TOOLKIT: {
img = LoadImageByToolkit(url);
break;
}
}
}catch(Exception e){
System.out.println("Exception "+e+" while attempting to load image "+url.toExter
nalForm()+"\n
Attempting to use fallback loading");
}
if((null == img || img.getWidth(null) == -1) && fallback){
switch (fallbackType) {
case LOAD_IMAGEICON: {
img = LoadImageByImageIcon(url);
break;
}
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(url);
break;
}
case LOAD_TOOLKIT: {
img = LoadImageByToolkit(url);
break;
}
}
}
waitForImage(img);
if(img!=null && (img instanceof java.awt.image.BufferedImage || img instanceof
java.awt.image.VolatileImage)){
img=tryToMakeAnAutomaticImage(img);
}
return img;
}
public Image loadImage(InputStream is){
Image img = null;
switch (loadType) {
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(is);
break;
}
}
if((null == img || img.getWidth(null) == -1) && fallback){
switch(fallbackType){
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(is);
break;
}
}
}
waitForImage(img);
if(img!=null && (img instanceof java.awt.image.BufferedImage || img instanceof
java.awt.image.VolatileImage)){
img=tryToMakeAnAutomaticImage(img);
}
return img;

}
public Image loadImage(ImageInputStream iis){
Image img = null;
switch (loadType) {
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(iis);
break;
}
}
if((null == img || img.getWidth(null) == -1) && fallback){
switch(fallbackType){
case LOAD_IMAGEI0: {
img = LoadImageByImageIO(iis);
break;
}
}
}
waitForImage(img);
if(img!=null && (img instanceof java.awt.image.BufferedImage || img instanceof
java.awt.image.VolatileImage)){
img=tryToMakeAnAutomaticImage(img);
}
return img;
}
public Image LoadImageByImageIcon(File filename){
ImageIcon ii = new ImageIcon(filename.getAbsolutePath());
return ii.getImage();
}
public Image LoadImageByToolkit(File filename){
return c.getToolkit().getImage(filename.getAbsolutePath());
}
public Image LoadImageByImageIO(File filename) {
Image img = null;
try{
img = ImageIO.read(filename);
}catch(IOException ioe){
System.out.println("Error loading image \'"+filename.getAbsolutePath()+"\'.");
ioe.printStackTrace();
}
return img;
}
public Image LoadImageByImageIO(URL url) {
Image img = null;
try{
img = ImageIO.read(url);
}catch(IOException ioe){
System.out.println("Error loading image \'"+url.toExternalForm()+"\'.");
ioe.printStackTrace();
}
return img;
}
public Image LoadImageByImageIcon(URL url){
ImageIcon ii = new ImageIcon(url);
return ii.getImage();
}
public Image LoadImageByToolkit(URL url){
return c.getToolkit().getImage(url);
}
public Image LoadImageByImageIO(InputStream stream) {
Image img = null;

try{
img = ImageIO.read(stream);
}catch(IOException ioe){
System.out.println("Error loading image.");
ioe.printStackTrace();
}
return img;
}
public Image LoadImageByImageIO(ImageInputStream istream) {
Image img = null;
try{
img = ImageIO.read(istream);
}catch(IOException ioe){
System.out.println("Error loading image.");
ioe.printStackTrace();
}
return img;
}
public Image tryToMakeAnAutomaticImage(Image img){
if(null != c){
waitForImage(img);
int width, height;
width = img.getWidth(null);
height =img.getHeight(null);
Image newimg = c.createImage(width, height);
if (null != newimg) {
Graphics g = newimg.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
img.flush();
img=newimg;
}
}
waitForImage(img);
return img;
}
public java.io.FileFilter getImageFileFilter(){
if(null==iff){
iff=new ImageFileFilter();
}
return iff;
}
class ImageFileFilter implements java.io.FileFilter {
public boolean accept(File pathname) {
if(pathname.isDirectory() )
return true;
String[] alltypes = getSupportedTypesArray();
for(int i=0;i<alltypes.length;i++){
if(pathname.getName().toUpperCase().endsWith("."+alltypes[i].toUpperCase())){
return true;
}
}
if(fallback){
String[] alltypes2 = getSupportedTypesArray(fallbackType);
for(int i=0;i<alltypes2.length;i++){
if(pathname.getName().toUpperCase().endsWith("."+alltypes2[i].toUpperCase())){
return true;
}
}
}

return false;
}
public String getDescription() {
return "Image File ("+getSupportedTypesSearchString()+")";
}
}
public javax.swing.filechooser.FileFilter getImageFileChooserFilter(){
if(null==ifcf){
ifcf=new ImageFileChooserFilter();
}
return ifcf;
}
class ImageFileChooserFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File pathname) {
if(pathname.isDirectory() )
return true;
String[] alltypes = getSupportedTypesArray();
for(int i=0;i<alltypes.length;i++){
if(pathname.getName().toUpperCase().endsWith("."+alltypes[i].toUpperCase())){
return true;
}
}
if(fallback){
String[] alltypes2 = getSupportedTypesArray(fallbackType);
for(int i=0;i<alltypes2.length;i++){
if(pathname.getName().toUpperCase().endsWith("."+alltypes2[i].toUpperCase())){
return true;
}
}
}
return false;
}
public String getDescription() {
return "Image File";
}
}
public void waitForImage(Image img){
MediaTracker tracker = new MediaTracker(c);
tracker.addImage(img, 0); // Image to track
try {
tracker.waitForID(0);
} catch (InterruptedException e) {
//System.out.println(e); // Exception...
}
}
public static void waitForImage(ImageIcon ii){
int status = ii.getImageLoadStatus();
while(status != MediaTracker.ERRORED && status != MediaTracker.COMPLETE){
ii.getImage();
try{
Thread.sleep(50);
}catch(InterruptedException ie){}
status = ii.getImageLoadStatus();
}
}
//*************** Image Resize Code *********************
public static Image resizeImage(Image img, int width, int height, int method){
switch(method){
case Image.SCALE_DEFAULT:{
img = img.getScaledInstance(width, height,Image.SCALE_DEFAULT);

break;
}
case Image.SCALE_FAST:{
img = img.getScaledInstance(width, height,Image.SCALE_FAST);
break;
}
case Image.SCALE_SMOOTH:{
img = img.getScaledInstance(width, height,Image.SCALE_SMOOTH);
break;
}
case Image.SCALE_REPLICATE:{
img = img.getScaledInstance(width, height,Image.SCALE_REPLICATE);
break;
}
case Image.SCALE_AREA_AVERAGING:{
img = img.getScaledInstance(width, height,Image.SCALE_AREA_AVERAGING);
break;
}
case SCALE_SMOOTH_ENLARGER:{
img = SmoothImageUpscaler.scaleImage(img,width,height);
break;
}
default:{
img = img.getScaledInstance(width, height,Image.SCALE_SMOOTH);
break;
}
}
return img;
}
public Image resizeImageAspect(Image img, int maxsize,int method){
int w, h, nw, nh;
w = img.getWidth(null);
h = img.getHeight(null);
if (w > maxsize || h > maxsize) {
int max = Math.max(w, h);
if (max == w) {
nw = maxsize;
nh = (int) (h * ( (double) maxsize / (double) w));
if (nh == 0) {
nh = 1;
}
} else {
nh = maxsize;
nw = (int) (w * ( (double) maxsize / (double) h));
if (nw == 0) {
nw = 1;
}
}
img = resizeImage(img,nw, nh, method);
}
return img;
}
//*************** Create Image Code *********************
public Image createImage(ImageProducer ip){
return c.createImage(ip);
}
public Image createImage(int w, int h){
return c.createImage(w,h);
}
//**************** Save Image Code **********************

public void saveImage(BufferedImage img,File filename, ImageWriter iw){


try{
ImageOutputStream ios = ImageIO.createImageOutputStream(filename);
iw.setOutput(ios);
iw.write(img);
ios.close();
}catch(Exception e){
System.out.println("IO Error:"+e.getClass().getName()+" - "+e.getLocalizedMessag
e());
e.printStackTrace();
}
}
public Vector getImageWriters(){
Vector v=new Vector();
String[] formats=null;
String[] format1=ImageIO.getWriterFormatNames();
for(int i=0;i<format1.length;i++){
if((format1[i]!="wbmp")&&(format1[i]!="WBMP"))
{
formats = format1;
}
else
{
i++;
}
}
java.util.Arrays.sort(formats);
for(int i=0;i<formats.length;i++){
Iterator it = ImageIO.getImageWritersByFormatName(formats[i]);
while(it.hasNext()){
if((format1[i]!="wbmp")&&(format1[i]!="WBMP"))
{
ImageWriter iw = (ImageWriter)it.next();
v.add(new ImageWriterWrapper(formats[i],iw));
}
else
{
ImageWriter iw = (ImageWriter)it.next();
}
}
}
return v;
}
public class ImageWriterWrapper{
String writerName = "";
ImageWriter writer=null;
String format;
public ImageWriterWrapper(String format, ImageWriter iw){
String iwname = iw.toString();
this.format = format;
if(iwname.length()>50){
String temp;
temp=iwname.substring(0,iwname.indexOf(".",iwname.indexOf(".")+1));
temp+="..."+iwname.substring(iwname.lastIndexOf("."));
iwname=temp;
}
writerName=format+" "+iwname;
writer=iw;
}
public String toString(){

return
}
public
return
}
public
return
}
public
return
}
}
public
return
}
}

writerName;
ImageWriter getWriter(){
writer;
String getWriterName(){
writerName;
String getFormat(){
format;
Component getComponent(){
c;

You might also like