【求助】请问 一个 image 图片转换成Byte[]数组的问题

猴头 2013-03-08 04:17:17
RT,我有一个Image图片 格式不一定,然后我通过MemoryStream流将图片保存在一个Byte数组中,然后将整个Byte数组 以二进制的形式保存在文件里面,接着从该文件中读取字节留到byte数组, 再转换成 Image图片,那么在从文件中读取字节流的时候读取出来的数据保存在Byte数组里面,那么整个 byte数组 应该定义多大呢???

说 不好说清楚,我上代码吧,帮我看看 会不会 造成数组不够长的情况:
代码写入文件的:


System.IO.MemoryStream ms = new System.IO.MemoryStream();
this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] bytes = new byte[] { };
bytes = ms.GetBuffer();
outStream.writeByteArray(bytes);
//上面是转换为byte数组,下面这段是写入文件:
public void writeByteArray(byte[] bytes)
{
long length = bytes.Length;
byte[] tbs = BitConverter.GetBytes(length);
for (int i = 0; i < tbs.Length; i++)
{
writer.Write(tbs[i]);
}
for (int i = 0; i < bytes.Length; i++)
{
writer.Write(bytes[i]);
}
}



读取文件数据的代码:



public byte[] readBytesArray()
{
ulong temp = 0;
ulong length = (ulong)BitConverter.GetBytes(temp).Length;
byte[] byLen = new byte[length];
for (ulong i = 0; i < length; i++)
{
byLen[i] = cacheBuff[this.position++];
}
length = BitConverter.ToUInt64(byLen, 0);
byte[] bytes = new byte[length];
for (ulong i = 0; i < length; i++)
{
bytes[i] = cacheBuff[this.position++];
}

return bytes;
}

然后转换成image图片的代码如下:

byte[] bytes = inStream.readBytesArray();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(bytes,0,bytes.Length);
this._image = Bitmap.FromStream(ms);



这两段代码这样写,会不会造成 图片信息 丢失呢??

如果 有可能发生 异常的问题,那么 合理的写法 该如何写呢??

谢谢 大家 帮忙了

发到 这个 板块 也不知道 位置发的对不对

...全文
649 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
猴头 2013-03-13
  • 打赏
  • 举报
回复
引用 17 楼 liuchaolin 的回复:
FineUi内部资源调用类,直接拿去用,不用客气 C# code?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081……
winform 的 程序......
md5e 2013-03-13
  • 打赏
  • 举报
回复
FineUi内部资源调用类,直接拿去用,不用客气

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Reflection;
using System.IO;
using System.Drawing.Imaging;

namespace FineUI
{
    /// <summary>
    /// 资源处理程序
    /// </summary>
    public class ResourceHandler : IHttpHandler
    {
        /// <summary>
        /// 处理资源的请求
        /// </summary>
        /// <param name="context">Http请求上下文</param>
        public void ProcessRequest(HttpContext context)
        {
            string type = String.Empty, 
                typeValue = String.Empty,
                resName = "FineUI.";
                

            if (!String.IsNullOrEmpty(typeValue = context.Request.QueryString["icon"]))
            {
                type = "icon";
            }
            else if (!String.IsNullOrEmpty(typeValue = context.Request.QueryString["js"]))
            {
                type = "js";
                resName += "js." + typeValue;
            }
            else if (!String.IsNullOrEmpty(typeValue = context.Request.QueryString["lang"]))
            {
                type = "lang";
                resName += "js.lang." + typeValue;
            }
            else if (!String.IsNullOrEmpty(typeValue = context.Request.QueryString["theme"]))
            {
                type = "theme";
                resName += "res.theme." + typeValue;
            }
            else if (!String.IsNullOrEmpty(typeValue = context.Request.QueryString["css"]))
            {
                type = "css";
                resName += "res.css." + typeValue;
            }
            else if (!String.IsNullOrEmpty(typeValue = context.Request.QueryString["img"]))
            {
                type = "img";
                resName += "res.img." + typeValue;
            }

            byte[] binary;
            switch (type)
            {
                case "icon":
                    if (!typeValue.EndsWith(".png") && !typeValue.EndsWith(".gif"))
                    {
                        typeValue = IconHelper.GetName((Icon)Enum.Parse(typeof(Icon), typeValue));
                    }
                    //resName += "res.icon." + typeValue;
                    string serverPath = String.Format("{0}/{1}", GlobalConfig.GetIconBasePath(), typeValue);
                    context.Response.WriteFile(context.Server.MapPath(serverPath));

                    context.Response.ContentType = "image/" + GetImageFormat(typeValue);
                    break;
                case "js":
                case "lang":
                    context.Response.Write(ResourceHelper.GetResourceContent(resName));
                    context.Response.ContentType = "text/javascript";
                    break;
                case "css":
                    context.Response.Write(ResourceHelper.GetResourceContent(resName));
                    context.Response.ContentType = "text/css";
                    break;
                case "theme":
                case "img":
                    binary = ResourceHelper.GetResourceContentAsBinary(resName);
                    context.Response.OutputStream.Write(binary, 0, binary.Length);
                    //context.Response.Write(ResourceHelper.GetResourceContent(resName));
                    context.Response.ContentType = "image/" + GetImageFormat(resName);
                    break;
            }

            
            // 缓存一年,只能通过改变 URL 来强制更新缓存
            context.Response.Cache.SetExpires(DateTime.Now.AddYears(1));
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
        }

        //private void RenderImage(HttpContext context, string resName)
        //{
        //    Assembly assembly = Assembly.GetExecutingAssembly();
        //    using (Stream stream = assembly.GetManifestResourceStream(resName))
        //    {
        //        using (System.Drawing.Image image = System.Drawing.Image.FromStream(stream))
        //        {
        //            // PNG输出时出现“GDI+ 中发生一般性错误”
        //            using (MemoryStream ms = new MemoryStream())
        //            {
        //                image.Save(ms, image.RawFormat);
        //                ms.WriteTo(context.Response.OutputStream);
        //                context.Response.ContentType = "image/" + GetImageFormat(image.RawFormat);
        //            }
        //        }
        //    }
        //}

        private string GetImageFormat(string imageName)
        {
            int lastDotIndex = imageName.LastIndexOf(".");
            if (lastDotIndex >= 0)
            {
                return imageName.Substring(lastDotIndex + 1);
            }
            return "png";
        }

        private string GetImageFormat(ImageFormat format)
        {
            if (format == ImageFormat.Bmp)
            {
                return "bmp";
            }
            else if (format == ImageFormat.Gif)
            {
                return "gif";
            }
            else if (format == ImageFormat.Jpeg)
            {
                return "jpeg";
            }
            else if (format == ImageFormat.Png)
            {
                return "png";
            }
            else if (format == ImageFormat.Tiff)
            {
                return "tiff";
            }
            else if (format == ImageFormat.Icon)
            {
                return "icon";
            }
            return "gif";
        }


        /// <summary>
        /// 只要请求的 URL 相同,则请求可以重用
        /// </summary>
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}
猴头 2013-03-13
  • 打赏
  • 举报
回复
关于 保存 成文件在读取后 背景色变黑的 问题解决了,不同的格式的图片,按照自己的格式保存,在读取 就可以了, 比如:


 System.IO.MemoryStream ms = new System.IO.MemoryStream();
            if (System.Drawing.Imaging.ImageFormat.Bmp.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            }
            else if (System.Drawing.Imaging.ImageFormat.Emf.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Emf);
            }
            else if (System.Drawing.Imaging.ImageFormat.Exif.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Exif);
            }
            else if (System.Drawing.Imaging.ImageFormat.Gif.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            }
            else if (System.Drawing.Imaging.ImageFormat.Jpeg.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else if (System.Drawing.Imaging.ImageFormat.MemoryBmp.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.MemoryBmp);
            }
            else if (System.Drawing.Imaging.ImageFormat.Png.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            }
            else if (System.Drawing.Imaging.ImageFormat.Icon.Guid.ToString().Equals(this.imageType))
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            }
            else
            {
                this._image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
但是 第一个 问题呢???? 就是防止 文件 太大 保存 可能 越界 .. 有更好的方法吗?
猴头 2013-03-12
  • 打赏
  • 举报
回复
引用 14 楼 cl61917380 的回复:
语言不同,初步估计是多写了字节。写入数据的字节长度应该可变。
不会的,如果多谢入或者 少写入字节了,那么 在接下来的数据读取中就会出错的
coooliang 2013-03-12
  • 打赏
  • 举报
回复
语言不同,初步估计是多写了字节。写入数据的字节长度应该可变。
猴头 2013-03-12
  • 打赏
  • 举报
回复
引用 11 楼 卷心菜 的回复:
文件格式是BNG?
本来我想 按照原始的格式储存的,但是 原始的格式 获取不到
猴头 2013-03-12
  • 打赏
  • 举报
回复
引用 11 楼 卷心菜 的回复:
文件格式是BNG?
Png的格式,但是保存的时候都转换成jpg了
卷心菜 2013-03-12
  • 打赏
  • 举报
回复
文件格式是BNG?
猴头 2013-03-12
  • 打赏
  • 举报
回复
又出问题了~~~~~~~~~~~
又出问题了~~~~~~~~~~~

本来 保存到二进制文件中的图片是透明色的,如图:



但是 重新从文件中读取出来后,背景色变成了黑色的了,如图:



这回事什么情况啊,保存文件的代码在上面呢.....

猴头 2013-03-09
  • 打赏
  • 举报
回复
引用 8 楼 sp1234 的回复:
http://msdn.microsoft.com/zh-cn/library/system.io.fileinfo.length(v=vs.100).aspx
这样不行啊,文件里面 还存有别的二进制数据呢,不仅仅是 图片的 二进制数据啊
猴头 2013-03-08
  • 打赏
  • 举报
回复
猴头 2013-03-08
  • 打赏
  • 举报
回复
求教 来帮忙啊
wang1986614 2013-03-08
  • 打赏
  • 举报
回复
google
zoedaid 2013-03-08
  • 打赏
  • 举报
回复
围观坐等解答··
Louis-Lv 2013-03-08
  • 打赏
  • 举报
回复
路过。。围观
Alessandro_ 2013-03-08
  • 打赏
  • 举报
回复
猴头 2013-03-08
  • 打赏
  • 举报
回复
读写 image 图片 以二进制的刑事保存在文件中 ,是根据 现有的要求这么做的.

4,816

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 图表区
社区管理员
  • 图表区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧