<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageService {
/**
* 将网络图片编码为base64
*
* @return
* @throws
*/
public static String factoryBase(String StoragePath) {
try {
URL url = new URL(StoragePath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
byte[] data = outStream.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(data);
return base64;
} catch (Exception e) {
return "";
}
}
public static String base64Image(String url) {
if (url.indexOf("http") > -1) {
String base64 = factoryBase(url);
if (base64 != "") {
return resizeImageTo40K(base64);
}
}
return "";
}
public static BufferedImage base64String2BufferedImage(String base64string) {
BufferedImage image = null;
try {
InputStream stream = BaseToInputStream(base64string);
image = ImageIO.read(stream);
} catch (IOException e) {
}
return image;
}
// BufferedImage转换成base64,在这里需要设置图片格式,如下是jpg格式图片:
public static String imageToBase64(BufferedImage bufferedImage) {
Base64 encoder = new Base64();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "jpg", baos);
} catch (IOException e) {
}
return new String(encoder.encode((baos.toByteArray())));
}
private static InputStream BaseToInputStream(String base64string) {
ByteArrayInputStream stream = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64string);
stream = new ByteArrayInputStream(bytes1);
} catch (Exception e) {
// TODO: handle exception
}
return stream;
}
public static String resizeImageTo40K(String base64Img) {
try {
BufferedImage src = base64String2BufferedImage(base64Img);
BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
String base64 = imageToBase64(output);
if (base64.length() - base64.length() / 8 * 2 > 40000) {
output = Thumbnails.of(output).scale(1 / (base64.length() / 40000)).asBufferedImage();
base64 = imageToBase64(output);
}
return base64;
} catch (Exception e) {
return base64Img;
}
}
}
网友评论