Uploaded image for project: 'Commons Imaging'
  1. Commons Imaging
  2. IMAGING-164

Simplify code in IcoImageParser::writeImage

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 1.0-alpha1
    • 1.0-alpha2
    • Format: ICO

    Description

      org.apache.commons.imaging.formats.ico.IcoImageParser::writeImage(final BufferedImage src, final OutputStream os, final ImagingParameters params)
      may throw an unexpected NullPointerException because it of the following code:

      final SimplePalette palette = paletteFactory.makeExactRgbPaletteSimple(src, 256);
      

      Then asking if the created palette is null. I will discuss where it comes from below. For now it is interesting that we set the variable bitCount despite the SimplePalette is null. Currently this makes no sense because the code will throw a NullPointerException later if SimplePalette is null.

      if (palette == null) {
                  if (hasTransparency) {
                      bitCount = 32;
                  } else {
                      bitCount = 24;
                  }
      

      In the later for-loop we try to call getPaletteIndex(rgb) on the SimplePalette instance. If it contains null, we'll get a NullPointerException here.

      for (int y = src.getHeight() - 1; y >= 0; y--) {
                  for (int x = 0; x < src.getWidth(); x++) {
                      final int argb = src.getRGB(x, y);
                      if (bitCount < 8) {
                          final int rgb = 0xffffff & argb;
                          final int index = palette.getPaletteIndex(rgb); // possible NullPointerException
                         ...
                      } else if (bitCount == 8) {
                          final int rgb = 0xffffff & argb;
                          final int index = palette.getPaletteIndex(rgb);  // possible NullPointerException
      

      Why can SimplePalette be null? It comes from PaletteFactory::makeExactRgbPaletteSimple(final BufferedImage src, final int max). As it's javadoc says it will "fails by returning null if there are more than max colors necessary":

      if (rgbs.add(rgb) && rgbs.size() > max) {
                          return null;
                      }
      

      My first idea goes to throw a RunTimeException rather than returning null. But one has to check if there are cases where the return of null triggers some error handling i.e. increasing the number of colors or creating a different type of object.

      Attachments

        Activity

          People

            kinow Bruno P. Kinoshita
            mgmechanics Michael Groß
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: