MiniQuark
MiniQuark

Reputation: 48446

How do you save an array to a PNG image in RAM using Julia?

Saving an image to a PNG file is not a problem, the following code works fine (using Julia 1.5, FileIO 1.4.1 and ImageIO 0.3.0):

using FileIO

image = rand(UInt8, 200, 150, 3)
save("test.png", image)

However, I cannot find how to save the PNG image to a RAM buffer instead. I tried this:

io = IOBuffer()
save(Stream(format"PNG", io), image)
data = take!(io)

There's no error, but the resulting data is much too small: just 809 bytes (instead of about 90kB for the test.png file).

What am I doing wrong?

Upvotes: 2

Views: 668

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

Your I/O code is correct but you are incorrectly generating the random image.

It should be:

using Images
image = [RGB(rand(N0f8,3)...) for x in 1:200, y in 1:150]

Now both the png file and buffer will have the same size in bytes (since png is compressed the exact number will vary with each randomized run):

julia> save(Stream(format"PNG", io), image)
90415

Upvotes: 2

Related Questions