Skip to content

Saving an RGB image as PNG can result in a grayscale image #150

Open
@nstiurca

Description

@nstiurca

If I have an RGB image where it so happens that for each pixel, all the channel values are the same, then saving it as a PNG results in a grayscale image.

Minimal example to reproduce:

import ImageMagick   # import first because of JuliaIO/ImageMagick.jl#140
using FileIO
using Colors

img = [RGB(0.5, 0.5, 0.5)]
fname, io = mktemp()
save(format"PNG", io, img)
close(io)
readlines(`file $fname`)[1]

And I get something like "/tmp/tmpbfYfcd: PNG image data, 1 x 1, 1-bit grayscale, non-interlaced".

I've looked around, and this seems to be a default optimization ImageMagick performs when saving PNGs in order to produce the smallest PNG possible.

The resultant workaround is to "convert" the file back to RGB by explicitly setting the PNG color type to RGB, such as by doing this in Julia:

run(`convert $fname -define png:color-type=2 $fname`)

This obviously an extremely hacky workaround. I would much prefer to control the output color type directly when saving the image; this workaround would get even uglier if trying to save to an arbitrary IO stream instead of directly to a file.

Version info:

Julia Version 1.1.0
Commit 80516ca202 (2019-01-21 21:24 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.1 (ORCJIT, skylake)
Environment:
  JULIA_PROJECT = /home/nicu/codes
  JULIA_EDITOR = atom -a
  JULIA_NUM_THREADS = 6

Project status:

  [336ed68f] CSV v0.4.3
  [324d7699] CategoricalArrays v0.5.2
  [5ae59095] Colors v0.9.5
  [150eb455] CoordinateTransformations v0.5.0
  [a93c6f00] DataFrames v0.17.1
  [5789e2e9] FileIO v1.0.5
  [4381153b] ImageDraw v0.1.0
  [92ff4b2b] ImageFeatures v0.2.0
  [6218d12a] ImageMagick v0.7.1
  [916415d5] Images v0.17.2
  [a98d9a8b] Interpolations v0.11.2
  [682c06a0] JSON v0.20.0
  [438e738f] PyCall v1.18.5+ #master (https://github.com/JuliaPy/PyCall.jl.git)
  [ade2ca70] Dates 
  [10745b16] Statistics 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions