I want to export many PNG pictures using Mathematica. However, it takes too much time. To make matters worse, sometimes it suddenly aborts. With any pictures, I have same problem.

For example, I Import about 1000 pictures of 2000x2000 pixels as "imagelist" and then each of them are divided into 20x20 pixels using:

part = ImagePartition[#, 20] & /@ imagelist;
data= Flatten[part]

There are now 10000 pictures.

namelist =  StringJoin["/Users/Documents/no", ToString[#], ".png"]&/@Range[10000]

Then I try to export:


If the number of Picture is hundreds, the above works. However, if the number is more than several thousands, it stops or becomes too slow.

  • 1
    $\begingroup$ You should not load so many images into Mathematica as you will quickly exceed all available memory. 1000 2000x2000 RGB(A) images requires 1000*2000*2000*4 bytes, when the PNGs are decompressed (about 15GB!). Instead, consider out-of-core methods, or Import and Export in a Do loop. If you do this first, you can then look into a ParallelDo to batch process them. $\endgroup$
    – flinty
    Mar 8 at 16:52
  • $\begingroup$ Oh, thank you so much!! I tried your code, and found it really fast. Also thank you for your kind guidance. Until then, I struggled many times.Therefore, I'm so grateful to you!! $\endgroup$
    – rani
    Mar 9 at 14:55

1 Answer 1


I would do something like this, and avoid loading everything into memory at once:

processImage[imgfile_] := 
 Module[{img, parts, i = 0, base = FileBaseName[imgfile]},
  img = Import[imgfile, "PNG"];
  parts = Flatten[ImagePartition[img, 20]];
  i = 0;
   With[{path = 
      StringTemplate["/Users/Documents/`b`_`n`.png"][<|"b" -> base, "n" -> i|>]},
    Export[path, p];
   , {p, parts}

imagefiles = {"test1.png", "test2.png"};
 , {imgfile, imagefiles}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.