문제

바이트 배열이 소스로 이미지 객체를 만들려고합니다. 내가 뭘 잘못하고 있죠?

소스 데이터로 바이트 배열로 이미지 객체를 초기화하려고 할 때 예외가 발생합니다. 예외는 아래 코드에 표시됩니다.

public class MyClass
{
    publuc System.Windows.Media.Imaging.BitmapImage InstanceImage { get; set; }

    public void GetImage()
    {
        // Retrieves a list of custom "Item" objects that contain byte arrays.
        // ScvClnt is our service client. The PollQueue method is designed to return information to us.
        lstQueue = SvcClnt.PollQueue(1);

        // This condition always evaluates as True, since we requested exactly 1 "Item" from the service client.
        if (lstQueue.Count == 1)
        {
            // lstQueue[0].InstanceImage is a byte array containing the data from an image file.
            // I have confirmed that it is a valid TIFF image file, by writing it to disk and opening it in MSPaint.
            if (lstQueue[0].InstanceImage != null)
            {
                // This condition is also True, since the image is just under 3KB.
                if (lstQueue[0].InstanceImage.Length > 0)
                {
                    this.InstanceImage = new System.Windows.Media.Imaging.BitmapImage();
                    this.InstanceImage.BeginInit();
                    this.InstanceImage.StreamSource = new System.IO.MemoryStream(lstQueue[0].InstanceImage);
                    InstanceImage.EndInit();
                    // The call to EndInit throws a NullReferenceException.
                    // {"Object reference not set to an instance of an object."}
                    // I have confirmed that this.InstanceImage and this.InstanceImage.StreamSource are not null at this point.
                    // They are successfully assigned in the lines of code above.
                } else InstanceImage = null;
            } else InstanceImage = null;
        } else InstanceImage = null;
    }
}

지구상에서 무엇이 잘못 될 수 있는지 전혀 모른다.
모든 조언은 대단히 감사 할 것입니다.

도움이 되었습니까?

해결책 2

이 MSDN 포럼 게시물 이 예제는 솔루션으로 사용합니다.

using (MemoryStream stream = new MemoryStream(abyteArray0))
{
    image.Source = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}

//The field image should be of type System.Windows.Controls.Image.

스트림을 매개 변수로만 가져 오는 BitMapFrame.create 메소드를 사용했으며 매력처럼 작동했습니다.

다른 팁

나는 당신이 언뜻보기에 당신의 수업과 함께하려는 일을 따르고 있는지 확실하지 않지만 원래 질문을 해결하기 위해 이것을 촬영하십시오.

    public static Image ConvertByteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top