1. 程式人生 > >影象儲存時候對壓縮格式的處理

影象儲存時候對壓縮格式的處理

最近在處理影象的時候,原來是CCITT T.6的,經過Batmap  的 Save(Stream, ImageFormat) 方法,結果影象壓縮格式改變為 LZW的壓縮格式,這樣影響了程式的後續處理,最後修改為呼叫Save(Stream, ImageCodecInfo, EncoderParameters) 來儲存,程式碼如下:

public static byte[] BitmapToBytes(Bitmap bitmap)
        {
            ImageCodecInfo myImageCodecInfo;
            System.Drawing.Imaging.Encoder myEncoder;
            myEncoder = System.Drawing.Imaging.Encoder.Compression;
            EncoderParameters myEncoderParameters;
            myImageCodecInfo = GetEncoderInfo("image/tiff");
            EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, (long)EncoderValue.CompressionCCITT4);
            myEncoderParameters = new EncoderParameters(1);
            myEncoderParameters.Param[0] = myEncoderParameter;
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                bitmap.Save(ms, myImageCodecInfo, myEncoderParameters);
                byte[] byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();
                return byteImage;
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;

            encoders = ImageCodecInfo.GetImageDecoders();
            for (j = 0; j < encoders.Length; j++)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }