图片转换类
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Xml;
namespace ImagesApp
{
class ImagesHelper
{
/// <summary>
/// 将字节数组进行压缩后返回压缩的字节数组
/// </summary>
/// <param name="data">需要压缩的数组</param>
/// <returns>压缩后的数组</returns>
public static byte[] Compress(byte[] data)
{
MemoryStream stream = new MemoryStream();
GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress);
gZipStream.Write(data, 0, data.Length);
gZipStream.Close();
return stream.ToArray();
}
/// <summary>
/// 解压字符数组
/// </summary>
/// <param name="data">压缩的数组</param>
/// <returns>解压后的数组</returns>
public static byte[] Decompress(byte[] bytes)
{
using (MemoryStream tempMs = new MemoryStream())
{
using (MemoryStream ms = new MemoryStream(bytes))
{
GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);
Decompress.CopyTo(tempMs);
Decompress.Close();
return tempMs.ToArray();
}
}
}
public static string Compress(string str)
{
//因输入的字符串不是Base64所以转换为Base64,因为HTTP如果不传递Base64则会发生http 400错误
return Convert.ToBase64String(Compress(Convert.FromBase64String(Convert.ToBase64String(Encoding.Default.GetBytes(str)))));
}
public byte[] GetPictureData(string imagepath)
{
try
{
/**/
////根据图片文件的路径使用文件流打开,并保存为byte[]
FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法
byte[] byData = new byte[fs.Length];
fs.Read(byData, 0, byData.Length);
fs.Close();
return byData;
}
catch (System.Exception e)
{
return null;
}
}
private static BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
{
BitmapImage bmp = null;
try
{
bmp = new BitmapImage();
bmp.BeginInit();
bmp.StreamSource = new MemoryStream(byteArray);
bmp.EndInit();
}
catch
{
bmp = null;
}
return bmp;
}
/// <summary>
/// BitmapImage转ByteArray
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
private static byte[] BitmapImageToByteArray(BitmapImage bmp)
{
byte[] byteArray = null;
try
{
Stream sMarket = bmp.StreamSource;
if (sMarket != null && sMarket.Length > 0)
{
//很重要,因为Position经常位于Stream的末尾,导致下面读取到的长度为0。
sMarket.Position = 0;
using (BinaryReader br = new BinaryReader(sMarket))
{
byteArray = br.ReadBytes((int)sMarket.Length);
}
}
//Console.WriteLine(sMarket.Length.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return byteArray;
}
public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}
//反过来,16进制格式的string 转成byte[],例如, "ae00cf"转换成0xae00cf,长度缩减一半;"3031" 转成new byte[]{ 0x30, 0x31}:
public static byte[] GetBytes(string hexString, out int discarded)
{
discarded = 0;
string newString = "";
char c;
// remove all none A-F, 0-9, characters
for (int i = 0; i < hexString.Length; i++)
{
c = hexString[i];
if (Uri.IsHexDigit(c))
newString += c;
else
discarded++;
}
// if odd number of characters, discard last character
if (newString.Length % 2 != 0)
{
discarded++;
newString = newString.Substring(0, newString.Length - 1);
}
int byteLength = newString.Length / 2;
byte[] bytes = new byte[byteLength];
string hex;
int j = 0;
for (int i = 0; i < bytes.Length; i++)
{
hex = new String(new Char[] { newString[j], newString[j + 1] });
bytes[i] = HexToByte(hex);
j = j + 2;
}
return bytes;
}
private static byte HexToByte(string hex)
{
byte tt = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
return tt;
}
/// <summary>
/// 字符串转BitmapImage
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public static BitmapImage ToBitmapImage(string Value)
{
string hexValue = Value;
byte[] imageByte = Convert.FromBase64String(hexValue);
imageByte = Decompress(imageByte);
BitmapImage imgSource = ByteArrayToBitmapImage(imageByte);
return imgSource;
}
/// <summary>
/// BitmapImage转字符串
/// </summary>
/// <param name="bi"></param>
/// <returns></returns>
public static string toString(BitmapImage imgSource)
{
try
{
byte[] imageByte = BitmapImageToByteArray(imgSource);
byte[] sourceData2 = Compress(imageByte);
string recString = Convert.ToBase64String(sourceData2);
return recString;
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
return "";
}
}
}
标题
private void Button_Click_2(object sender, RoutedEventArgs e)
{
//选择图片
//最好使用WPF原生OpenFileDialog
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Title = "选择文件";
openFileDialog.Filter = "图片(*.bmp;*.gif;*.jpg;*.png)|*.bmp;*.gif;*.jpg;*.png";
openFileDialog.FileName = string.Empty;
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
openFileDialog.DefaultExt = "jpg";
bool? result = openFileDialog.ShowDialog();
if (result != true)
{
return;
}
string fileName = openFileDialog.FileName;
BitmapImage image = new BitmapImage();
FileStream m_ImageStream = new FileStream(fileName, FileMode.Open);
image.BeginInit();
image.StreamSource = m_ImageStream;
image.EndInit();
// BitmapImage转字符串
var _zp = ImagesHelper.toString(image);
//保存进数据库
....
}