日期:2014-05-17  浏览次数:21039 次

写了一个图像文件转二进制文件的小程序,可是有个很费解的问题
就是我将二进制文件转化成图像文件先没有保存,显示在PictureBox中 可以
但是直接取PictureBox中的图像文件转换成二进制文件 代码中
Bitmap.Save(ms, Bitmap.RawFormat)这句会报错:出现一般性的GDI问题,之前报错出现空值,但是bitmap和bitmap.RawFormat不为空啊

如果将二进制转化成的图像保存在硬盘中的图像文件中,读到PictureBox中,在转化成二进制文件却可以。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace IMGToBinary
{
    class IMGToBinaryHelper
    {

        public static Bitmap BytesToBitmap(byte[] Bytes)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(Bytes);
                return new Bitmap(stream);
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        public static byte[] BitmapToBytes(Bitmap Bitmap)
        {
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                ImageFormat imageFormat = Bitmap.RawFormat;
                Bitmap.Save(ms, Bitmap.RawFormat);
                byte[] byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();