Package com. mobi5.commons. utils;
Import java. AWT. image;
Import java. AWT. image. bufferedimage;
Import java. Io. file;
Import java. Io. filenotfoundexception;
Import java. Io. fileoutputstream;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import javax. ImageIO. ImageIO;
Import com.sun.image.codec.jpeg. Unzip codec;
Import com.sun.image.codec.jpeg. Unzip encodeparam;
Import com.sun.image.codec.jpeg. encode imageencoder;
Public class imageziputil {
/**
* Compressing image files <br>
* First save the original file, then compress and upload it.
*
* @ Param oldfile
* Full path of the file to be compressed
* @ Param width
* Width
* @ Param height
* Height
* @ Param Quality
* Quality
* @ Param smallicon
* Suffix of a small image
* @ Return returns the full path of the compressed file.
*/
Public static string zipimagefile (string oldfile, int width, int height,
Float quality, string smallicon ){
If (oldfile = NULL ){
Return NULL;
}
String newimage = NULL;
Try {
/** Process temporary files on the server */
Image srcfile = ImageIO. Read (new file (oldfile ));
/** Width and height setting */
Bufferedimage tag = new bufferedimage (width, height,
Bufferedimage. type_int_rgb );
Tag. getgraphics (). drawimage (srcfile, 0, 0, width, height, null );
String fileprex = oldfile. substring (0, oldfile. indexof ('.'));
/** Compressed file name */
Newimage = fileprex + smallicon
+ Oldfile. substring (fileprex. Length ());
/** Temporary storage location after compression */
Fileoutputstream out = new fileoutputstream (newimage );
Required imageencoder encoder = required codec. createjpegencoder (out );
Incluencodeparam Jep = inclucodec. getdefaultincluencodeparam (TAG );
/** Compression Quality */
Jep. setquality (quality, true );
Encoder. encode (TAG, JEP );
Out. Close ();
} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Return newimage;
}
/**
* Save the file to the temporary path on the server
*
* @ Param filename
* @ Param is
* @ Return file full path
*/
Public static string writefile (string filename, inputstream is ){
If (filename = NULL | filename. Trim (). Length () = 0 ){
Return NULL;
}
Try {
/** Save it to a temporary file first */
Fileoutputstream Fos = new fileoutputstream (filename );
Byte [] readbytes = new byte [512]; // buffer size
Int readed = 0;
While (readed = is. Read (readbytes)> 0 ){
FOS. Write (readbytes, 0, readed );
}
FOS. Close ();
Is. Close ();
} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Return filename;
}
}