Message Boards Message Boards

Convert .jp2 image to .png increase image size significantly

Due to an API I am using doesn't accept .jp2 format images, I will have to convert those images into .png.

I wrote a simple script to maintain the original data's directory:

JP2ToPNG[fileName_]:= Module[
    	{newFileName, filePath},
    	filePath = StringSplit[fileName, "/"] /."NcomSampleData"-> "PNG";
    	filePath[[-1]] = StringReplace[filePath[[-1]], ".jp2" -> ".png"];
    	newFileName = StringJoin[Riffle[filePath[[3;;]], "/"]];
    	filePath = StringJoin[Riffle[StringSplit[newFileName, "/"][[3;;-2]], "/"]];
    	If[
    		DirectoryQ[filePath], 
    		FileConvert[fileName -> newFileName],
    		CreateDirectory[filePath]; 
    		FileConvert[fileName -> newFileName]
    	]
    ]

But then I found that the new .png file are 2-4 times larger than the original ones. I am guessing the reason is the original data, every pixel is 1 Byte, 8 bit integer range from 0-255. But Mathematica read it as grayscale and save it as a float number 4 bytes from (0,1)?

Can anyone confirm with my guess? If I am guessing correctly, how to fix this problem?

Thanks!

Attachment

Attachments:
POSTED BY: Wenzhen Zhu

PNG uses different compression algorithm than JPEG2000, but here are some ideas that you can try.

Input file:

In[1]:= file = "ExampleData/girl.jp2";
In[2]:= i = Import[file];
In[3]:= FileSize[FindFile[file]]
Out[3]= Quantity[10.909, "Kilobytes"]

Export with default settings:

In[4]:= FileSize[Export["out1.png", i]]
Out[4]= Quantity[53.595, "Kilobytes"]

Binarize image before exporting:

In[5]:= FileSize[Export["out2.png", Binarize[i]]]
Out[5]= Quantity[1.321, "Kilobytes"]

Use color palette of length 8:

In[6]:= FileSize[Export["out3.png", i, "ColorMapLength" -> 8]]
Out[6]= Quantity[6.269, "Kilobytes"]
POSTED BY: Piotr Wendykier
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract