문제

이 코드는 바이트 배열에서로드 된 이미지의 썸네일을 반환합니다. 저자가 4 개의 메모리 스트림을 사용하는 이유를 이해하려고 노력하고 있으며이를 다시 작성하는 간단한 방법이 있거나 괜찮은지 여부가 있는지 이해하려고합니다.

public Image GetThumbnail(int height, int width)
{
    //load the image from a byte array (imageData)
    using (MemoryStream mem = new MemoryStream(this.imageData))
    {
        // Create a Thumbnail from the image
        using (Image thumbPhoto = Image.FromStream(mem, 
            true).GetThumbnailImage(height, width, null, 
            new System.IntPtr()))
        {
            // Convert the Image object to a byte array
            using (MemoryStream ms = new MemoryStream())
            {
                thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                using (MemoryStream m = new MemoryStream(ms.ToArray()))
                {
                    return Image.FromStream(m, true);
                }
            }
        }
   }
}
도움이 되었습니까?

해결책

그는 실제로 여기에서 3 개의 메모리 스트림 만 사용하고 있지만 2 만 사용하면됩니다 (저는 생각합니다). 이 코드를 대체 할 수 있어야합니다.

using (MemoryStream m = new MemoryStream(ms.ToArray()))                
{                    
    return Image.FromStream(m, true);                
}

이것으로 :

ms.Seek(0, SeekOrigin.Begin);
return Image.FromStream(ms, true);

나는 그가 세 번째 메모리 스트림을 만들었다 고 생각합니다 ms 메모리 스트림은 처음에 없었습니다.

다른 팁

public Image GetThumbnail(int height, int width)
{
    //load the image from a byte array (imageData)
    using (MemoryStream mem = new MemoryStream(this.imageData))
    {
        // Create a Thumbnail from the image
        using (Image thumbPhoto = Image.FromStream(mem, 
            true).GetThumbnailImage(height, width, null, 
            new System.IntPtr()))
        {
            return thumbPhoto;
        }
   }
}

나는 이것이 옳을 것이라고 생각한다

저자가 JPEG로 변환을 강요하고 있다는 이전 답변은 누락되었다고 생각합니다.

나는 마지막이라고 생각할 것입니다. m, 제거 될 수 있습니다. 단순히 재설정 ms.Position=0 충분할 것입니다. 주요 절약은 ms.ToArray().

다른 메모리 스트림은 필요해 보이거나 적어도 그것들을 제거하거나 재사용하여 얻을 수있는 것이 거의 없습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top