我有以下的轉換器在我的WPF應用程序:我可以處理這個流嗎?
[ValueConversion(typeof(byte[]), typeof(ImageSource))]
public class ReturnLabelImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var byteArray = value as byte[];
if (byteArray == null)
return new BitmapImage();
return BuildReturnLabelImageSource(byteArray);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public static ImageSource BuildReturnLabelImageSource(byte[] image)
{
if (image == null)
return null;
var imgBrush = new BitmapImage
{
CacheOption = BitmapCacheOption.OnLoad,
CreateOptions = BitmapCreateOptions.PreservePixelFormat
};
imgBrush.BeginInit();
imgBrush.StreamSource = ConvertImageToMemoryStream(image);
imgBrush.EndInit();
return imgBrush;
}
public static MemoryStream ConvertImageToMemoryStream(byte[] img)
{
var ms = new MemoryStream(img);
return ms;
}
}
我的代碼評審給我的建議,即流應該進行處理。我不明白我該怎麼做;我想出了最好的想法是:
public static ImageSource BuildReturnLabelImageSource(byte[] image)
{
if (image == null)
return null;
var imgBrush = new BitmapImage
{
CacheOption = BitmapCacheOption.OnLoad,
CreateOptions = BitmapCreateOptions.PreservePixelFormat
};
using (var stream = ConvertImageToMemoryStream(image))
{
imgBrush.BeginInit();
imgBrush.StreamSource = stream;
imgBrush.EndInit();
return imgBrush;
}
}
我在正確的軌道這裏,或者我應該這樣做是不同的?
你爲什麼不問你的代碼審查? –
我做到了;以下是他的迴應:「如果可以的話,我寧願放棄它,儘管我對imageource不夠熟悉並知道如何實現這一點。」 (我可能是我的團隊中最熟悉的WPF)。我想我會跟進更多的觀衆,以確保我們的理由是正確的。 –