Stream/Bytes[]/Image对象相互转化

原文链接:http://www.knowsky.com/897888.html

Stream转Byte数组、Image转Byte数组、文件转Stream等
这里写图片描述

/// <summary>
/// 1、将 Stream 转成 byte[]
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static byte[] StreamToBytes(Stream stream)
{
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
    // 设置当前流的位置为流的开始
    stream.Seek(0, SeekOrigin.Begin);
    return bytes;
}
/// <summary>
/// 2、将 byte[] 转成 Stream
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static Stream BytesToStream(byte[] bytes)
{
    Stream stream = new MemoryStream(bytes);
    return stream;
}
// <summary> 
/// 3、字节流转换成图片 
/// </summary> 
/// <param name="byt">要转换的字节流</param> 
/// <returns>转换得到的Image对象</returns> 
public static Image BytToImg(byte[] byt)
{
    try
    {
        MemoryStream ms = new MemoryStream(byt);
        Image img = Image.FromStream(ms);
        return img;
    }
    catch (Exception ex)
    {
        LogHelper.WriteError("StreamHelper.BytToImg 异常", ex);
        return null;
    }
}
/// <summary>
///  4、图片转换成字节流 
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static byte[] ImageToByteArray(Image img)
{
    ImageConverter imgconv = new ImageConverter();
    byte[] b = (byte[])imgconv.ConvertTo(img, typeof(byte[]));
    return b;
}
/// <summary>
/// 5、把图片Url转化成Image对象
/// </summary>
/// <param name="imageUrl"></param>
/// <returns></returns>
public static Image Url2Img(string imageUrl)
{
    try
    {
        if (string.IsNullOrEmpty(imageUrl))
        {
            return null;
        }

        WebRequest webreq = WebRequest.Create(imageUrl);
        WebResponse webres = webreq.GetResponse();
        Stream stream = webres.GetResponseStream();
        Image image;
        image = Image.FromStream(stream);
        stream.Close();

        return image;
    }
    catch (Exception ex)
    {
        LogHelper.WriteError("StreamHelper.Url2Img 异常", ex);
    }

    return null;
}
/// <summary>
/// 6、把本地图片路径转成Image对象
/// </summary>
/// <param name="imagePath"></param>
/// <returns></returns>
public static Image ImagePath2Img(string imagePath)
{
    try
    {
        if (string.IsNullOrEmpty(imagePath))
        {
            return null;
        }

        byte[] bytes = Image2ByteWithPath(imagePath);
        Image image = BytToImg(bytes);
        return image;
    }
    catch (Exception ex)
    {
        LogHelper.WriteError("StreamHelper.ImagePath2Img 异常", ex);
        return null;
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值