Keep image compressed Java - java

I have a server and I want to compress images in it. When I write the image, it goes from 23MB to 650kb and it's okay. But when I'm reading it to send it to my client app, the size is back to 23MB.
public static BufferedImage getProfilePicture(String username) throws IOException {
File input = new File(profilePicturePath + File.separatorChar + username + ".png");
BufferedImage image = ImageIO.read(input);
rewriteImage(image);
return image;
}
public static String getProfilePictureBase64(String username) throws IOException {
BufferedImage img = getProfilePicture(username);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "png", os);
return Base64.getEncoder().encodeToString(os.toByteArray());
}
So my question is : How can I keep the compressed size to send image to my client ?

Related

How to attach custom/existing screenshot in allure report?

Generally, I am using below code to take a screenshot and attach in allure report :
#Attachment(value = "Page Screenshot", type = "image/png")
public static byte[] saveScreenshotPNG(WebDriver driver) {
return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
}
But now my need is I have already some screenshot on my desktop and want to attach it with an allure report. is that possible?
You can take the existing image and convert it to byte[]. getScreenshotAs() decodes the screenshot string so you might need to do it as well
Java
#Attachment(value = "Page Screenshot", type = "image/png")
public static byte[] saveScreenshotPNG(String path) {
File file = new File(path);
BufferedImage bufferedImage = ImageIO.read(file);
byte[] image = null;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
ImageIO.write(bufferedImage, "png", bos);
image = bos.toByteArray();
} catch (Exception e) { }
// if decoding is not necessary just return image
return image != null ? Base64.getMimeDecoder().decode(image) : null;
}
Python
with open(path, 'rb') as image:
file = image.read()
byte_array = bytearray(file)
allure.attach(byte_array, name="Screenshot", attachment_type=AttachmentType.PNG)

How to send back an image from a server? (edited)

I have a webserver that creates a QRcode. During the process, I get a BarcodeQRCode object from which I can get the image (.getImage()).
I am not sure how I can send back to the client this image. I don't want to save it in a file but just send back data in response to JSON request.
For information, I have a similar case from which I get a PDF file that works great:
private ByteArrayRepresentation getPdf(String templatePath, JSONObject json) throws IOException, DocumentException, WriterException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(..., baos);
// setup PDF content...
return new ByteArrayRepresentation(baos.toByteArray(), MediaType.APPLICATION_PDF);
}
Is there a way to do something similar more or less like:
private ByteArrayRepresentation getImage(JSONObject json) throws IOException, DocumentException, WriterException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Image qrCode = getQRCode(json); /// return the BarcodeQRCode.getImage()
ImageIO.write(qrCode, "png", baos);
return new ByteArrayRepresentation(baos.toByteArray(), MediaType.IMAGE_PNG);
}
But this is not working. I get: argument mismatch; Image cannot be converted to RenderedImage.
EDIT
No compilation error after modification as proposed below. However, the returned image seems to be empty (or at least not normal). I put the error-free code if anyone has an idea what is wrong:
#Post("json")
public ByteArrayRepresentation accept(JsonRepresentation entity) throws IOException, DocumentException, WriterException {
JSONObject json = entity.getJsonObject();
return createQR(json);
}
private ByteArrayRepresentation createQR(JSONObject json) throws IOException, DocumentException, WriterException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Image codeQR = getQRCode(json);
BufferedImage buffImg = new BufferedImage(codeQR.getWidth(null), codeQR.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
buffImg.getGraphics().drawImage(codeQR, 0, 0, null);
return new ByteArrayRepresentation(baos.toByteArray(), MediaType.IMAGE_PNG);
}
private Image getQRCode(JSONObject json) throws IOException, DocumentException, WriterException {
JSONObject url = json.getJSONObject("jsonUrl");
String urls = (String) url.get("url");
BarcodeQRCode barcode = new BarcodeQRCode(urls, 200, 200, null);
Image codeImage = barcode.createAwtImage(Color.BLACK, Color.WHITE);
return codeImage;
}
First, convert the Image to RenderedImage:
BufferedImage buffImg = new BufferedImage(qrCode.getWidth(null), qrCode.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
buffImg.getGraphics().drawImage(qrCode, 0, 0, null);
If you use com.itextpdf.text.Image you can use this code
BarcodeQRCode qrcode = new BarcodeQRCode("testo testo testo", 1, 1, null);
Image image = qrcode.createAwtImage(Color.BLACK, Color.WHITE);
BufferedImage buffImg = new BufferedImage(image.getWidth(null), image.getWidth(null), BufferedImage.TYPE_4BYTE_ABGR);
buffImg.getGraphics().drawImage(image, 0, 0, null);
buffImg.getGraphics().dispose();
File file = new File("tmp.png");
ImageIO.write(buffImg, "png", file);
I hope you have been helpful
Enrico

Display Image in base64 java HttpServer

How to display Base64 string in image on Java com.sun.net.httpserver.HttpServer ?
I run this code:
static class base implements HttpHandler{
#Override
public void handle(HttpExchange he) throws IOException {
byte[] name = Base64.getEncoder().encode(base64String.getBytes());
byte[] decodedString = Base64.getDecoder().decode(new String(name).getBytes("UTF-8"));
String base64String = "BASE64 IMAGE";
Headers headers = he.getResponseHeaders();
headers.add("Content-Type", "image/png");
File file = new File ("1.png");
//System.out.println(file);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream bufferedInputStream = new ByteArrayInputStream(decodedString);
bufferedInputStream.read(decodedString, 0, decodedString.length);
he.sendResponseHeaders(200, decodedString.length);
final OutputStream os = he.getResponseBody();
os.write(decodedString);
os.close();
}
}
But displays a white cube

RMI Client/Server - File Transfer

I want to implement a Java program where a client will be able to upload a file(image, text etc) from the client side and it being sent to the server side where the file will be stored in a folder on the server computer.
Is this possible and realistic? Is EJB a better way of doing this? Are there any good resources available?
You can create a class in a common package as follows, then call createByteArray() from client-side and convert image into a byte array. Then pass it into a skeleton and reconstruct an image using createBufferedImage(). Finally, save it as a JPEG using toFile():
/**
*
* #author Randula
*/
public class TransportableImage {
/**
*
* #param bufferedImage
* #return
* #throws IOException
*/
public byte[] createByteArray(BufferedImage bufferedImage)
throws IOException {
byte[] imageBytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder jpg = JPEGCodec.createJPEGEncoder(bos);
jpg.encode(bufferedImage);
bos.flush();
imageBytes = bos.toByteArray();
bos.close();
return imageBytes;
}
//Reconstruct the BufferedImage
public BufferedImage createBufferedImage(byte[] imageBytes)
throws IOException {
InputStream is = new ByteArrayInputStream(imageBytes);
JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(is);
BufferedImage image = decoder.decodeAsBufferedImage();
is.close();
return image;
}
//Save a JPEG image
public void toFile(File file, byte[] imageBytes)
throws IOException {
FileOutputStream os = new FileOutputStream(file);
os.write(imageBytes, 0, imageBytes.length);
os.flush();
os.close();
}
}

How to upload an image using ByteArrayOutputStream in Vaadin?

I want to receive an uploaded image as a byte array (so that it can be inserted into a sql database).
I also want to show the uploaded image as a preview.
I have tried the following code but im not receiving the bytes of the full image. (if i print the byte array it prints only a few characters)
final Embedded preview = new Embedded("Uploaded Image");
preview.setVisible(false);
final Upload upload = new Upload();
upload.setCaption("Image");
// Create upload stream
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Stream to write to
upload.setReceiver(new Upload.Receiver() {
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
return baos; // Return the output stream to write to
}
});
upload.addSucceededListener(new Upload.SucceededListener() {
#Override
public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
final byte[] bytes = baos.toByteArray();
preview.setVisible(true);
preview.setSource(new StreamResource(new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
return new ByteArrayInputStream(bytes);
}
}, ""));
}
});
image.setSource(new StreamResource(new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
return new ByteArrayInputStream(baos.toByteArray());
}
}, ""));
You could try adding a ProgressListener with some logs to the Upload to see what is happening; you will get the amount of read bytes and total content length as a parameter to the updateProgress method so you can see if everything is being sent.

Categories