Compress picture size
@Log4j2
public class Base64Util {
/**
* Compressed images within 100k
*
* @param base64Img
* @return
*/
public static String resizeImageTo100K(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;
}
}
/**
* base64 convert to BufferedImage
*
* @param base64string
* @return
*/
public static BufferedImage base64String2BufferedImage(String base64string) {
BufferedImage image = null;
try {
InputStream stream = BaseToInputStream(base64string);
image = ImageIO.read(stream);
} catch (IOException e) {
log.info("");
}
return image;
}
/**
* Base64 convert to InputStream
*
* @param base64string
* @return
*/
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;
}
/**
* BufferedImage switch to base64
*
* @param bufferedImage
* @return
*/
public static String imageToBase64(BufferedImage bufferedImage) {
Base64 encoder = new Base64();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "jpg", baos);
} catch (IOException e) {
log.info("");
}
return new String(encoder.encode((baos.toByteArray())));
}
}
Read More:
- MultipartFile Upload an Image Example
- Docker: How to build a rabbitmq image cluster
- Hutool Excel Import & Export Example
- File class details (get the file name, size, path, create, etc.)
- Canvas: How to Implement Video Screenshot Function
- Windows Core Audio APIs: How to Progress Loopback Recording and Generate WAV File
- Jquery use queue to implement Ajax request queue Simple Example
- Android: How to Add Background Music for Activity with Service
- Flutter & Dart every() Method Example
- Flutter & Dart Regular Expression Examples
- MAFIA: 1- OpenFlow statistics (Counters, Timestamps)(mafia-sdn/p4demos/demos/1-openflow/1.1-statistics/p4src/of.p4)
- Matplotlib Draw 3D scatter Diagram Example
- torch.max Example (How to Use)
- How to Use Printf in HAL Library
- Flutter & Dart Enumeration Example
- Opentelemetry + Jaeger Python Version Cross Service Call Example
- Android: How to get the size of font you set (Example Code)
- Websocket Front-end Call Example
- Open CASCADE Technology 7.7.0 released
- WCNSS_qcom_cfg.ini WIFI Configuration File Guide