sream bytes[]img相互変換

9238 ワード

/// <summary>

///   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>

///   byte[]   Stream

/// </summary>

/// <param name="bytes"></param>

/// <returns></returns>

public static Stream BytesToStream(byte[] bytes)

{

    Stream stream = new MemoryStream(bytes);

    return stream;

}



/// <summary> 

///   

/// </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>

///    

/// </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>

///  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>

///  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;

    }

}