首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

写了一个图像文件转二进制文件的小程序,可是有个很费解的有关问题

2013-12-06 
写了一个图像文件转二进制文件的小程序,可是有个很费解的问题就是我将二进制文件转化成图像文件先没有保存

写了一个图像文件转二进制文件的小程序,可是有个很费解的问题
就是我将二进制文件转化成图像文件先没有保存,显示在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();
                return byteImage;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }
        }

    }
}




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;

namespace IMGToBinary
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void BtnReadFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();


            openFileDialog.Filter = "文本文件 (*.txt)|*.txt|图片文件 (*.jpg,*.jpeg,*.bmp,*.png)|" +
                "*.jpg;*.jpeg;*.bmp;*.png|All files (*.*)|*.*";

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog.FileName;
                TxtReadFile.Text = fileName;
                string extension = Path.GetExtension(fileName);
                switch (extension)
                {
                    case ".txt":
                    case ".xml":
                        string text = File.ReadAllText(fileName, Encoding.Default);//执行了四布操作,打开,读取,关闭
                        //File.ReadAllLines();
                        RtbBinFile.Text = text;
                        break;
                    case ".jpg":
                    case ".bmp":
                    case ".png":
                        PicboxIMG.Image = new Bitmap(fileName);
                        break;
                    default:
                        MessageBox.Show("文件格式错误,可以选择jeg,bmp,png或者txt,xml文件");
                        break;

                }
            }
        }

        private void BtnIMGToBinary_Click(object sender, EventArgs e)
        {
            if (PicboxIMG.Image != null)
            {
                byte[] binaryIMG = IMGToBinaryHelper.BitmapToBytes((Bitmap)PicboxIMG.Image);

                StringBuilder strBuilder = new StringBuilder();
                if (binaryIMG != null)
                {
                    for (int i = 0; i < binaryIMG.Length; i++)
                    {
                        strBuilder.Append(binaryIMG[i].ToString("X2"));
                    }
                }

                RtbBinFile.Text = strBuilder.ToString();

            }
            else
                MessageBox.Show("图片文件不存在");
        }



        private void BtnBinaryToIMG_Click(object sender, EventArgs e)
        {
            if (RtbBinFile.Text != "")
            {
                string binaryFile = RtbBinFile.Text;
                binaryFile = binaryFile.Replace(" ", "");
                if ((binaryFile.Length % 2) != 0)
                    binaryFile += " ";
                byte[] returnBytes = new byte[binaryFile.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(binaryFile.Substring(i * 2, 2), 16);

                Bitmap image = IMGToBinaryHelper.BytesToBitmap(returnBytes);
                PicboxIMG.Image = image;

            }
            else
                MessageBox.Show("二进制文本文件不存在");
        }

        private void BtnSaveIMG_Click(object sender, EventArgs e)
        {
            if (PicboxIMG.Image != null)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "图片文件 (*.jpg)|*.jpg|图片文件 (*.bmp)|*.bmp|图片文件 (*.png)|*.png|All files (*.*)|*.*";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string saveFile = saveFileDialog.FileName;
                    string extension = Path.GetExtension(saveFile);
                    switch(extension)
                    {
                        case ".jpg":
                            PicboxIMG.Image.Save(saveFile, ImageFormat.Jpeg);
                            break;
                        case ".bmp":
                            PicboxIMG.Image.Save(saveFile, ImageFormat.Bmp);
                            break;
                        case ".png":
                            PicboxIMG.Image.Save(saveFile, ImageFormat.Png);
                            break;
                        default:
                            break;
                    }


                }
            }
            else
                MessageBox.Show("没有图片文件");
        }

        private void BtnSaveBinary_Click(object sender, EventArgs e)
        {
            if (RtbBinFile.Text != "")
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "文本文件 (*.txt)|*.txt|All files (*.*)|*.*";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string saveFile = saveFileDialog.FileName;
                    FileStream fs = new FileStream(saveFile, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(RtbBinFile.Text);

                    sw.Close();
                    fs.Close();
                }
            }
            else
                MessageBox.Show("没有文本文件");
        }
    }
}



我感觉是从二进制转图像的时候丢失了某个格式信息,所以用这个刚从二进制转过来的图像转不了二进制文件
而图像保存的时候自动加了这个信息,所以从文件读入图像,在转二进制文件却可以。

我只是猜的,不知道具体什么问题,怎么解决,求帮助啊
[解决办法]
save成bmp即可。
[解决办法]
引用:
Quote: 引用:

BytesToBitmap函数中把stream.Close();去掉
因为函数的返回值是new Bitmap(stream),这个返回值后来给了PicboxIMG,当再将图像转成2进制的时候,因为和PicboxIMG关联的MemoryStream已经被关闭,这样在Bitmap.Save(ms, Bitmap.RawFormat);这里就会出错。

msdn对于new Bitmap(stream)中说过“在 Bitmap 的生存期内,必须使流保持打开。”

但是还有些问题, 就是将BytesToBitmap函数中return 这句改为return new Bitmap((Image)new Bitmap(stream));之后不管去掉还是不去掉stream.Close();都在相同的位置Bitmap.Save(ms, Bitmap.RawFormat);有值不能为 null。参数名: encoder

StackTrace:在 System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder,EncoderParameters encoderParams)\r\n   
            在 System.Drawing.Image.Save(Stream stream, ImageFormat format)\r\n   
            在 IMGToBinary.IMGToBinaryHelper.BitmapToBytes(Bitmap Bitmap) 位置 E:\\WorkProject\\Test Project\\MyTest\\IMGToBinary\\IMGToBinary\\IMGToBinaryHelper.cs:行号 43"string
在帮我看看,怎么回事,第一次就出现的这个错误,当我改过return那几后就出现刚解决的那个错误,帮我看看,如果解决我加分

return new Bitmap((Image)new Bitmap(stream));会重新生成一个实例,但是Bitmap的默认的格式(Bitmap.RawFormat)不被Save函数支持,你可以手动设定一个格式。
比如bmp.Save(ms, ImageFormat.Bmp);

热点排行