package com.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
public class ImgUtil {
static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
public static String getImgBASE64IO(String imgUrl) throws IOException{
File file = new File(imgUrl);
BufferedImage bi = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi,"jpg",baos);
byte[] bytes = baos.toByteArray();
return encoder.encode(bytes);
}
public static String getImgBASE64FromNetwork(String imgUrl) throws IOException{
URL url = new URL(imgUrl);
BufferedImage bi = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi,"jpg",baos);
byte[] bytes = baos.toByteArray();
return encoder.encode(bytes);
}
public static void getImg(String imgBASE64String,String imgUrl) throws IOException{
byte[] bytes = decoder.decodeBuffer(imgBASE64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedImage bi = ImageIO.read(bais);
File file = new File(imgUrl);
ImageIO.write(bi,"jpg",file);
}
public static void main(String[] args) throws IOException {
JFrame f = new JFrame();
MyCanvas mc = new MyCanvas();
String str = getImgBASE64IO("http://192.168.0.0:8080/file/fs/l/118342236118323200");
byte[] bytes = decoder.decodeBuffer(str);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedImage bi = ImageIO.read(bais);
mc.setImg(bi);
mc.repaint();
f.add(mc);
f.setSize(400,550);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
class MyCanvas extends Canvas{
private BufferedImage bi;
private Image img;
private int image_width;
private int image_height;
public void setImg(BufferedImage bi){
this.bi=bi;
this.zoom();
}
@Override
public void paint(Graphics g){
g.drawImage(img,0,0,this.getWidth(),this.getHeight(),this);
}
public void zoom(){
image_width=bi.getWidth();
image_height=bi.getHeight();
img = bi.getScaledInstance(image_width,image_height,Image.SCALE_SMOOTH);
}
}