今日已更新 305 条资讯 | 累计 19865 条内容
关于我们

How I export 1.2-gigapixel images on an iPhone without running out of memory

Yuiko Koyanagi 2026年07月14日 05:38 1 次阅读 来源:Dev.to

Rendering a big image on iOS is one of those things that looks trivial until your app gets killed by the OS mid-export. CGContext , draw, makeImage() , done — except the moment the output gets large, that innocent-looking pipeline quietly asks for gigabytes of RAM and iOS terminates you. I hit this wall building Mozary , an iOS app that packs 100+ photos into a single giant picture (a photo mosaic). In v1.1.0 I finally killed the "high-resolution export crashes with out-of-memory" bug for good. The fix: stop putting the canvas in RAM at all. Put it in a memory-mapped file and let the OS page it to disk. RAM usage dropped from "4.8 GB, please die" to a few dozen MB, flat, regardless of output size. This post is the walkthrough — with the actual Swift. If you've ever seen Core Graphics blow up on a big image (mosaics, collages, stitched panoramas, high-res rendering — same trap), this is for you. TL;DR A non-compressed bitmap costs 4 bytes/pixel . A 1.2-gigapixel image = ~4.8 GB of RAM just for the canvas. CGContext(data: nil, ...) allocates that in RAM. context.makeImage() then copies it again . Double death. Back the canvas with a memory-mapped file ( mmap ). Writes transparently page out to disk and don't count against your app's memory footprint . Wrap that same mapping in a CGImage via CGDataProvider — zero copy — and stream it straight to a JPEG on disk. Never call makeImage() . Decode source tiles at their draw size , not full size. Because you now spend disk instead of RAM: add a free-space pre-flight check and clean up temp files after a crash. Let's dig in. The problem: "compressed file size" is a lie about memory Mozary lays photos out on a grid. A typical high-res export is a 200 × 267 grid with each tile drawn at 150px : width: 200 × 150 = 30,000 px height: 267 × 150 = 40,050 px That's ~1.2 gigapixels . Here's the part people underestimate: the final JPEG is only a few hundred MB to ~2 GB because JPEG is compressed . But while you're drawing, the canvas i

本文内容来源于互联网,版权归原作者所有
查看原文