How can I calculate file size of resized image (for example JPEG) before I resize it?
I need to send HTTP request Content-length, then I will resize image, else nginx get me time out response.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
zen0n, if you absolutely have to do this, using Andrew’s suggestion with a minor modification is the only way to do it (do the entire resize operation, outputting the bytes to a ByteArrayOutputStream so you can count them before hand).
The modification I would use is doing this server-side with a simple image-resizing library like imgscalr, pass in the BufferedImage that represents the loaded image, and get back a resized BufferedImage that represents the new-sized image. Then pump it through ImageIO.write and output it to a BufferedArrayOutputStream.
Then set your “Content-Length” header and stream the image contents back.
Because converting raw image bytes to a JPG introduces a compression and encoding sequence of events, there is no accurate way to pre-predict the exact file length before hand and then use ImageIO.write to stream the bytes back to the client. You’ll have to resize the image completely first (in memory) using the technique mentioned above, THEN write the data back to the client.