def process_png(data)
      type   = 'png'
      width  = 0
      height = 0
      x_dpi  = 96
      y_dpi  = 96

      offset = 8
      data_length = data.size

      # Search through the image data to read the height and width in th the
      # IHDR element. Also read the DPI in the pHYs element.
      while offset < data_length

        length = data[offset + 0, 4].unpack("N")[0]
        png_type   = data[offset + 4, 4].unpack("A4")[0]

        case png_type
        when "IHDR"
          width  = data[offset +  8, 4].unpack("N")[0]
          height = data[offset + 12, 4].unpack("N")[0]
        when "pHYs"
          x_ppu = data[offset +  8, 4].unpack("N")[0]
          y_ppu = data[offset + 12, 4].unpack("N")[0]
          units = data[offset + 16, 1].unpack("C")[0]

          if units == 1
            x_dpi = x_ppu * 0.0254
            y_dpi = y_ppu * 0.0254
          end
        end

        offset = offset + length + 12

        break if png_type == "IEND"
      end
      raise "#{filename}: no size data found in png image.\n" unless height

      [type, width, height, x_dpi, y_dpi]
    end
def process_png(data)
      type   = 'png'
      width  = 0
      height = 0
      x_dpi  = 96
      y_dpi  = 96

      offset = 8
      data_length = data.size

      # Search through the image data to read the height and width in th the
      # IHDR element. Also read the DPI in the pHYs element.
      while offset < data_length

        length = data[offset + 0, 4].unpack("N")[0]
        png_type   = data[offset + 4, 4].unpack("A4")[0]

        case png_type
        when "IHDR"
          width  = data[offset +  8, 4].unpack("N")[0]
          height = data[offset + 12, 4].unpack("N")[0]
        when "pHYs"
          x_ppu = data[offset +  8, 4].unpack("N")[0]
          y_ppu = data[offset + 12, 4].unpack("N")[0]
          units = data[offset + 16, 1].unpack("C")[0]

          if units == 1
            x_dpi = x_ppu * 0.0254
            y_dpi = y_ppu * 0.0254
          end
        end

        offset = offset + length + 12

        break if png_type == "IEND"
      end
      raise "#{filename}: no size data found in png image.\n" unless height

      [type, width, height, x_dpi, y_dpi]
    end
Extract width and height information from a PNG file.