把图片生成Base64字符串

时间:2015-06-30 20:17:10   收藏:0   阅读:117
public class ImgeUtils {

    public static String img2String(BufferedImage img,String type){
        String imgStr  = null;
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        try {
            ImageIO.write(img, type, baos);
            
            byte[] imgByte = baos.toByteArray();
            
            imgStr = new BASE64Encoder().encode(imgByte);
        } catch (IOException ex) {
            Logger.getLogger(ImgeUtils.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            try {
                baos.close();
            } catch (IOException ex) {
                Logger.getLogger(ImgeUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        return imgStr;
    }
}
 public static void main(String[] args) {
        String imgStr = null;
        
        try {
            BufferedImage img = Thumbnails.of(
                    ImageIO.read(new File("/home/y/my_screen/markers.png"))
                ).size(100, 100).asBufferedImage();
            imgStr = ImgeUtils.img2String(img, "png");
        } catch (IOException ex) {
            Logger.getLogger(PngBase64Test.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        System.out.println("imgStr:"+imgStr);
    }

 

原文:http://www.cnblogs.com/yshyee/p/4611264.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!