BASE64Encoder_ImgTransform
2995 ワード
package cn.cnnic.api.client.commons;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* BASE64Encoder and Image transform
* @author Dengshimei
*/
public class ImgTransform
{
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
BASE64Decoder decoder = new sun.misc.BASE64Decoder();
public ImgTransform()
{
//Init or do something.
}
//BASE64Encoder to image file
public File base64StringToImage(String base64String, String imgName)
{
imgName = imgName.toLowerCase();
if(base64String != null && base64String.length() > 0)
{
File file = new File("cnnicUploadImgTemp" + File.separator + imgName + ".jpg"); //jpg, png, gif
try
{
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
ImageIO.write(bi1, "jpg", file); // ,
file.deleteOnExit(); //
return file;
}
catch (Exception e)
{
System.out.println("===== Run base64StringToImage method fail!");
}
}
return null;
}
//Image file to BASE64Encoder. Param:imgPath = d://pic3.jpg
public String getImageBinary(String imgPath)
{
if(imgPath != null && imgPath.length() > 0)
{
File file = new File(imgPath);
BufferedImage bufferedImage;
try
{
bufferedImage = ImageIO.read(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
return encoder.encodeBuffer(bytes).trim();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
//Files destroy
public void filesDestroy(File[] files)
{
for(int i = 0; i < files.length; i++)
{
if(files[i] != null && files[i].length() > 0)
{
files[i].delete();
}
}
files = null;
}
}