Jon*_*edo 14 c# wpf image bytearray
我正在尝试转换System.Windows.Controls.Image
为byte[]
和我不知道Image类中哪个方法可以帮助这个场景,顺便说一下我真的不知道该怎么做,因为在我的LINQ模型中该字段显示为Binary
类型,我必须更改如果我想将它保存为byte[]
类型?
我在这里发现了代码,但没有使用WPF:
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
PHJProjectPhoto myPhoto = new PHJProjectPhoto {
ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[]
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
Run Code Online (Sandbox Code Playgroud)
Jon*_*edo 32
真正的解决方案...当你的ORM上的数据库映射字段是Byte []/byte []/Bynary时,如果想从System.Windows.Control.Image保存jpg图像
public byte[] getJPGFromImageControl(BitmapImage imageC)
{
MemoryStream memStream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageC));
encoder.Save(memStream);
return memStream.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
呼叫:
getJPGFromImageControl(firmaUno.Source as BitmapImage)
Run Code Online (Sandbox Code Playgroud)
希望有帮助:)
gix*_*gix 13
我不知道你的Image是如何声明的,但假设我们有这个XAML声明:
<Image x:Name="img">
<Image.Source>
<BitmapImage UriSource="test.png" />
</Image.Source>
</Image>
Run Code Online (Sandbox Code Playgroud)
然后你可以将test.png的内容转换为像这样的字节数组:
var bmp = img.Source as BitmapImage;
int height = bmp.PixelHeight;
int width = bmp.PixelWidth;
int stride = width * ((bmp.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
bmp.CopyPixels(bits, stride, 0);
Run Code Online (Sandbox Code Playgroud)