2 Replies Latest reply: Aug 7, 2012 9:22 AM by 954254 RSS

    Overwriting an image with ImageWriter.write() does not  overwrite the file

    954254
      Hi,

      I need to save images in JPEG and specify which level of compression the JPEG algorithm uses.

      I've written some code, inspired by [1] that does the job. But:

      If I try to overwrite a big image with a small image (big and small in terms of file size), the content of the small image is correctly written but the file's size does not change, as the old file's content is not dropped.

      This bug is known (see [2]), but still open since 2003...

      I don't see how to apply the proposed solution from the bug report: "The proposed solution is reset length of the given RandomAccessFile instance to zero".

      Can somebody point me to the right direction ?

      Is there a way to re-open a bug (without submitting a new one) ?

      [1] http://blog.carsoncheng.ca/2011/02/how-to-change-jpeg-compression-in-java.html
      [2] http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4943659
        • 1. Re: Overwriting an image with ImageWriter.write() does not  overwrite the file
          gimbal2
          951251 wrote:
          Is there a way to re-open a bug (without submitting a new one) ?
          Nope, but the bug is not closed - just ignored for all eternity. Nobody but you seems to care about it.

          A work-around for this incredibly odd issue seems to be to simple delete an existing file before you attempt to write a new one.
          • 2. Re: Overwriting an image with ImageWriter.write() does not  overwrite the file
            954254
            I've found what the proposed solution is about.

            Instead of creating the FileImageOutputStream from a File, it needs to be created from a RandomAccessFile.
            This way, it is possible to reset the length of the RandomAccessFile to 0.
            RandomAccessFile raf = new RandomAccessFile(this.dst, "rw");
            raf.setLength(0);
            FileImageOutputStream imgOutStrm = new FileImageOutputStream(raf);
            Or we can truncate the RandomAccessFile before closing the FileImageOutputStream (which seems a bit more efficient).
            raf.setLength(raf.getFilePointer());
            imgOutStrm.close();
            A bit complicated for someone who just want to write an image to a file.