簡體   English   中英

使用JpegBitmapDecoder從字節數組加載圖像時出現ArgumentException

[英]ArgumentException when loading image from byte array using JpegBitmapDecoder

我在課堂上閱讀JPEG文件時遇到了一些麻煩。 我需要從JPEG文件加載元數據和位圖。 到目前為止,我有這個:

    public void Load()
    {
        using (Stream imageStream = File.Open(this.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            BitmapDecoder decoder = new JpegBitmapDecoder(imageStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
            BitmapSource source = decoder.Frames[0];

            // load metadata
            this.metadata = source.Metadata as BitmapMetadata;

            // prepare buffer
            int octetsPerPixel = source.Format.BitsPerPixel / 8;
            byte[] pixelBuffer = new byte[source.PixelWidth * source.PixelHeight * octetsPerPixel];
            source.CopyPixels(pixelBuffer, source.PixelWidth * octetsPerPixel, 0);

            Stream pixelStream = new MemoryStream(pixelBuffer);

            // load bitmap
            this.bitmap = new Bitmap(pixelStream); // throws ArgumentException
        }

        this.status = PhotoStatus.Loaded;
    }

但是Bitmap構造函數在嘗試從流中創建Bitmap實例時會拋出ArgumentException。

文件說:

System.ArgumentException

stream不包含圖像數據或為null。

-要么-

stream包含一個大小超過65,535像素的PNG圖像文件。

我不確定,我做錯了什么。 你能幫我么?

您正在使用Bitmap構造函數,它通常用於以已知格式加載圖像文件 - JPEG,PNG等。相反,您只是獲得了一堆字節,並且您沒有告訴它有關您的格式的任何信息想要使用它們。

目前尚不清楚為什么要使用BitmapDecoder和BitmapSource - 為什么你不只是使用:

Stream imageStream = File.Open(this.FilePath, FileMode.Open,
                               FileAccess.Read, FileShare.Read));
this.bitmap = new Bitmap(imageStream);

請注意,此處不得使用using語句 - 在調用構造函數后, Bitmap “擁有”流。

除了所有這些,你似乎試圖混合WPF和WinForms的圖像想法,我懷疑這是一個壞主意:(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM