我是 C# 新手。
我想转换FormatConvertedBitmap
为Stream
如前所述。我找不到任何方法。我想将 FormatConvertedBitmap 保存或写入文件,以便将其作为流读取,但甚至找不到将其写入文件的方法。
有人可以帮助我吗:
- 将 FormatConvertedBitmap 转换为流或
- 将 FormatConvertedBitmap 写入文件,然后将其作为 Stream 读取。
公共流图像
{
get
{//some condition
if (_image != null)
{
_image.Seek(0, SeekOrigin.Begin);
BitmapImage bmp = new BitmapImage();
MemoryStream stream = (MemoryStream)_image;
bmp.BeginInit();
bmp.StreamSource = stream;
bmp.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
bmp.EndInit();
var grayBitmapSource = new FormatConvertedBitmap();
grayBitmapSource.BeginInit();
grayBitmapSource.Source = bmp;
grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
grayBitmapSource.EndInit();
Stream st=new MemoryStream();
//File.WriteAllBytes(Path.GetTempPath(),grayBitmapSource);
return grayBitmapSource;
}
在上面的代码中,我从服务器获取 Image as Stream 然后在某些情况下我将其转换为 grayScale image 。但是现在我们应该返回一个 Stream,最后我们有了 FormatConvertedBitmap。
#####编辑public Stream Image
{
get
{
//some condition
if (_image != null)
{
_image.Seek(0, SeekOrigin.Begin);
BitmapImage bmp = new BitmapImage();
MemoryStream stream = (MemoryStream)_image;
bmp.BeginInit();
bmp.StreamSource = stream;
bmp.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
bmp.EndInit();
var grayBitmapSource = new FormatConvertedBitmap();
grayBitmapSource.BeginInit();
grayBitmapSource.Source = bmp;
grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
grayBitmapSource.EndInit();
int bytePerPixel = grayBitmapSource.Format.BitsPerPixel / 8;
int width = grayBitmapSource.PixelWidth;
int height = grayBitmapSource.PixelHeight;
int stride = width * bytePerPixel;
byte[] resultLine = new byte[height * stride];
grayBitmapSource.CopyPixels(resultLine, stride, 0);
MemoryStream ms = new MemoryStream(resultLine);
return ms;