base64 encoded image compression/resize
I had base64 encode image in string format. Need to compress/resize it to diffe开发者_如何学Gorent size, i.e. Image files created from these compressed/resized base64 encoded images are of different size.
What Compression/resize algorithm/jar can be used in Java?
The output of compression is almost always binary data, rather than a string... at which point it's pointless doing the base64 conversion to start with.
Images are usually compressed already (most formats use compression) so you won't actually get much benefit. If you do actually need the data in a string format, you could try compressing the original binary data first using GZipOutputStream
etc and then base64 encode it, but I doubt that you'll save much space.
I'm using this function to return an image .7 the size. (This was for screenshots returned from Selenium.... the image started looking pretty bad if I scaled it down too far.):
public String SeventyPercentBase64(String in_image)
{
String imageData = in_image;
//convert the image data String to a byte[]
byte[] dta = DatatypeConverter.parseBase64Binary(imageData);
try (InputStream in = new ByteArrayInputStream(dta);) {
BufferedImage fullSize = ImageIO.read(in);
// Create a new image .7 the size of the original image
double newheight_db = fullSize.getHeight() * .7;
double newwidth_db = fullSize.getWidth() * .7;
int newheight = (int)newheight_db;
int newwidth = (int)newwidth_db;
BufferedImage resized = new BufferedImage(newwidth, newheight, BufferedImage.SCALE_REPLICATE);
Graphics2D g2 = (Graphics2D) resized.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
//draw fullsize image to resized image
g2.drawImage(fullSize, 0, 0, newwidth, newheight, null);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write( resized, "png", baos );
baos.flush();
byte[] resizedInByte = baos.toByteArray();
Base64Encoder enc_resized = new Base64Encoder();
String out_image = enc_resized.encode(resizedInByte);
return out_image;
}
} catch (IOException e) {
System.out.println("error resizing screenshot" + e.toString());
return "";
}
}
精彩评论