How to resize an image in C# to a certain hard-disk size?

前端 未结 5 1527
野性不改
野性不改 2020-12-16 19:46

How to resize an image an image in C# to a certain hard-disk size, like 2MiB? Is there a better way than trial and error (even if it\'s approximate, of course).

Any

5条回答
  •  温柔的废话
    2020-12-16 20:13

    If it's a 24bit BMP i think you would need to do something like this:

    //initial size =  WxH
    long bitsperpixel = 24; //for 24 bit BMP
    double ratio;
    long size = 2 * 1 << 20;//2MB = 2 * 2^20
    size -= 0x35;//subtract the BMP header size from it
    long newH, newW, left, right, middle,BMProwsize;
    left = 1;
    right = size;//binary search for new width and height
    while (left < right)
    {
        middle = (left + right + 1) / 2;
        newW = middle;
        ratio = Convert.ToDouble(newW) / Convert.ToDouble(W);
        newH = Convert.ToInt64(ratio * Convert.ToDouble(H));
        BMProwsize = 4 * ((newW * bitsperpixel + 31) / 32);
        //row size must be multiple of 4
        if (BMProwsize * newH <= size)
            left = middle;
        else
            right = middle-1;                
    }
    
    newW = left;
    ratio = Convert.ToDouble(newW) / Convert.ToDouble(W);
    newH = Convert.ToInt64(ratio * Convert.ToDouble(H));
    //resize image to newW x newH and it should fit in <= 2 MB
    

    If it is a different BMP type like 8 bit BMP also in the header section there will be more data specifying the actual color of each value from 0 to 255 so you will need to subtract more from the total file size before the binary search.

提交回复
热议问题