private static BitmapImage ConvertToBitmap(byte[] bytes)
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(bytes);
bitmapImage.EndInit();
return bitmapImage;
}
private byte[] ConvertToBytes(BitmapSource bitmapSource)
{
byte[] buffer = null;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);
memoryStream.Position = 0;
if (memoryStream.Length > 0)
{
using (BinaryReader br = new BinaryReader(memoryStream))
{
buffer = br.ReadBytes((int)memoryStream.Length);
}
}
memoryStream.Close();
return buffer;
}
private static BitmapImage ConvertToBitmap(BitmapSource bitmapSource)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);
memoryStream.Position = 0;
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();
memoryStream.Close();
return bImg;
}
public static byte[] BitmapImageToBytes(BitmapImage bmp)
{
byte[] buffer = null;
try
{
Stream stream = bmp.StreamSource;
if (stream != null && stream.Length > 0)
{
//很重要,因?yàn)镻osition經(jīng)常位于Stream的末尾,導(dǎo)致下面讀取到的長度為0。
stream.Position = 0;
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((int)stream.Length);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return buffer;
}
BitmapSource to byte[] 互轉(zhuǎn)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 最近用到的各種數(shù)據(jù)類型的轉(zhuǎn)換方法,非原創(chuàng),親測可用,記錄如下: 【File轉(zhuǎn)byte數(shù)組、byte數(shù)組轉(zhuǎn)File】...
- ///////////////////////////// short //////////////////...
- /*** 將int數(shù)值轉(zhuǎn)換為占四個(gè)字節(jié)的Byte數(shù)組** @param intVal int 要轉(zhuǎn)換的int...
- 效果 把某個(gè)字節(jié)或字節(jié)數(shù)組轉(zhuǎn)換成字符串01的形式,一個(gè)字節(jié)用8個(gè)"0"或"1"字符表示。比如:byte(3) --...
- using Java NIO's ByteBuffer is very simple: Code1: output...