-1

Is there a way, in Java, to compute what the size of a compressed image will be w/o saving the image? (This will be used to determine the quality necessary to compress an image to a specific size.)

Something like this, but in Java instead of C#, and where the Stream can be a dead end.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • Java's `MemoryStream` equivalent is `ByteArrayOutputStream`. Once you compress the image you can [write it to that stream](https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#write(java.awt.image.RenderedImage,%20java.lang.String,%20java.io.OutputStream)), get the size in bytes and discard the stream. – BackSlash Jul 03 '19 at 12:49
  • @BackSlash: I fear the answer is to write my own, but is there a stream I could use that wouldn't even save the data in memory but still allow me to determine what the size *would* have been? – Scott Hunter Jul 03 '19 at 12:53
  • 1
    @ScottHunter AFAIK no default way. But you could extend InputStream and instead of storing the bytes just count the length. Should be painless – Matthew Kerian Jul 03 '19 at 12:59
  • @MatthewKerian: You mean *Out*putStream, right? – Scott Hunter Jul 03 '19 at 13:05
  • @ScottHunter Yeah, my bad – Matthew Kerian Jul 03 '19 at 13:20
  • @ScottHunter Updated it with a simple implementation – Matthew Kerian Jul 03 '19 at 13:26

1 Answers1

2

Here's a simple implementation.

public class LengthCounterOutputStream extends OutputStream{

    private int byteCounter = 0;

    @Override
    public void write(int b){
        byteCounter++;
    }

    @Override
    public void write(@NotNull byte[] b){
        this.write(b, 0, b.length);
    }

    @Override
    public void write(@NotNull byte[] b, int off, int len){
        byteCounter += len;
    }

    public int getByteCounter(){
        return byteCounter;
    }
}
Matthew Kerian
  • 812
  • 5
  • 18