1 11 package org.eclipse.swt.internal.image; 12 13 14 import java.io.*; 15 import org.eclipse.swt.*; 16 import org.eclipse.swt.graphics.*; 17 18 23 public abstract class FileFormat { 24 static final String FORMAT_PACKAGE = "org.eclipse.swt.internal.image"; static final String FORMAT_SUFFIX = "FileFormat"; static final String [] FORMATS = {"WinBMP", "WinBMP", "GIF", "WinICO", "JPEG", "PNG", "TIFF", "OS2BMP"}; 28 LEDataInputStream inputStream; 29 LEDataOutputStream outputStream; 30 ImageLoader loader; 31 int compression; 32 33 37 abstract boolean isFileFormat(LEDataInputStream stream); 38 39 abstract ImageData[] loadFromByteStream(); 40 41 45 public ImageData[] loadFromStream(LEDataInputStream stream) { 46 try { 47 inputStream = stream; 48 return loadFromByteStream(); 49 } catch (Exception e) { 50 if (e instanceof IOException) { 51 SWT.error(SWT.ERROR_IO, e); 52 } else { 53 SWT.error(SWT.ERROR_INVALID_IMAGE, e); 54 } 55 return null; 56 } 57 } 58 59 63 public static ImageData[] load(InputStream is, ImageLoader loader) { 64 FileFormat fileFormat = null; 65 LEDataInputStream stream = new LEDataInputStream(is); 66 boolean isSupported = false; 67 for (int i = 1; i < FORMATS.length; i++) { 68 if (FORMATS[i] != null) { 69 try { 70 Class clazz = Class.forName(FORMAT_PACKAGE + '.' + FORMATS[i] + FORMAT_SUFFIX); 71 fileFormat = (FileFormat) clazz.newInstance(); 72 if (fileFormat.isFileFormat(stream)) { 73 isSupported = true; 74 break; 75 } 76 } catch (ClassNotFoundException e) { 77 FORMATS[i] = null; 78 } catch (Exception e) { 79 } 80 } 81 } 82 if (!isSupported) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); 83 fileFormat.loader = loader; 84 return fileFormat.loadFromStream(stream); 85 } 86 87 91 public static void save(OutputStream os, int format, ImageLoader loader) { 92 if (format < 0 || format >= FORMATS.length) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); 93 if (FORMATS[format] == null) SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); 94 if (loader.data == null || loader.data.length < 1) SWT.error(SWT.ERROR_INVALID_ARGUMENT); 95 96 LEDataOutputStream stream = new LEDataOutputStream(os); 97 FileFormat fileFormat = null; 98 try { 99 Class clazz = Class.forName(FORMAT_PACKAGE + '.' + FORMATS[format] + FORMAT_SUFFIX); 100 fileFormat = (FileFormat) clazz.newInstance(); 101 } catch (Exception e) { 102 SWT.error(SWT.ERROR_UNSUPPORTED_FORMAT); 103 } 104 if (format == SWT.IMAGE_BMP_RLE) { 105 switch (loader.data[0].depth) { 106 case 8: fileFormat.compression = 1; break; 107 case 4: fileFormat.compression = 2; break; 108 } 109 } 110 fileFormat.unloadIntoStream(loader, stream); 111 } 112 113 abstract void unloadIntoByteStream(ImageLoader loader); 114 115 119 public void unloadIntoStream(ImageLoader loader, LEDataOutputStream stream) { 120 try { 121 outputStream = stream; 122 unloadIntoByteStream(loader); 123 outputStream.flush(); 124 } catch (Exception e) { 125 try {outputStream.flush();} catch (Exception f) {} 126 SWT.error(SWT.ERROR_IO, e); 127 } 128 } 129 } 130 | Popular Tags |