Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

c# - Cropping a JPG without loading all of it in memory

How can I crop a big JPG and extract a small portion of it? The problem is main JPGs are so big and I can't load all of it in memory. I used convert.exe from ImageMagick, but it's not working properly on all versions of windows and I prefer some C# method instead of a standalone exe.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of possibilities. You could use stream which is part of ImageMagick, or vips. Let's do stream first.

I can make a large (10,000x5,000) JPEG like this:

convert -size 10000x5000 xc:blue BigBoy.jpg

then use stream like this to extract a chunk 1,000x1,000 from an offset of 8,000+50

stream -extract 1000x1000+8000+50 BigBoy.jpg extract.rgb

and the extraact.rgb file is 3000000 bytes in size, i.e. 1,000x1,000 at 3 bytes/pixel.

If I do that with time -l you can see the resident set is small despite the large image

/usr/bin/time -l stream -extract 1000x1000+8000+50 BigBoy.jpg extract.rgb
        0.81 real         0.79 user         0.01 sys
   2924544  maximum resident set size       <----- 2MB RAM ****
         0  average shared memory size
         0  average unshared data size
         0  average unshared stack size
       796  page reclaims

You can then convert that extract.rgb to JPEG with convert

convert -size 1000x1000 -depth 8 extract.rgb chunk.jpg

I am no expert on vips, but you may have some success with this command that also shows the peak memory usage with the --vips-leak flag at the end

vips extract_area BigBoy.jpg SmallBoy.jpg 8000 50 1000 1000 --vips-leak
memory: high-water mark 8.72 MB

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...