Function Repository Resource:

ReadPNG

Source Notebook

Efficiently read a PNG file from disk and return the image

Contributed by: Arnoud Buzing

ResourceFunction["ReadPNG"][file]

reads file as a PNG image and returns the image.

Details and Options

ResourceFunction["ReadPNG"] returns $Failed if it can not read the file as a PNG image.
ResourceFunction["ReadPNG"] bypasses most of the functionality of the Import, making it less flexible and more limited, but significantly faster. It should be used judiciously when performance is critical.

Examples

Basic Examples (5) 

Export a random image as a PNG file:

In[1]:=
file = Export["test.png", RandomImage[1, {1000, 1000}]]
Out[1]=

Import the file with ReadPNG one hundred times, noting the elapsed time:

In[2]:=
timing1 = Do[ResourceFunction["ReadPNG"][file], 100] // AbsoluteTiming // First
Out[3]=

Repeat the same experiment with Import:

In[4]:=
timing2 = Do[Import[file], 100] // AbsoluteTiming // First
Out[4]=

Note how ReadPNG is significantly faster than Import:

In[5]:=
timing2/timing1
Out[5]=

ReadPNG only imports a file as an Image. Import provides many more options:

In[6]:=
Import[file, "Elements"]
Out[6]=

Properties and Relations (1) 

PNG importing can be made even faster by using the underlying symbol directly to avoid ResourceFunction overhead:

In[7]:=
readPNG = ResourceFunction["ReadPNG", "Function"]
Out[7]=
In[8]:=
timing1 = Do[readPNG[file], 100] // AbsoluteTiming // First
Out[8]=

Publisher

Arnoud Buzing

Version History

  • 1.0.0 – 06 July 2020

Related Resources

License Information