如何在C#中将原始二进制文件转换为图像 [英] How to convert a raw binary file into an image in C#

查看:109
本文介绍了如何在C#中将原始二进制文件转换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!

我需要在C#中找到一种方法来解析一个二进制文件,该文件包含2-2-2-2格式的原始数据(无标头,元数据,压缩等)中的图像.每种RGB颜色为2位,不透明度为2位.我需要阅读并显示结果图像.我是C#的新手,无法在帖子中找到相关答案,有什么想法吗?我正在使用VS 2008 Prof版.

AQ

Hello!

I need to find a way in C# to parse a binary file which contains an image in raw data (no headers, metadata, compresssion, etc.) in a 2-2-2-2 format. This is 2 bits for each RGB color and 2 bits for opacity. I need to read it and display the resulting image. I am new to C# and have not been able to find a relevant answer in the posts, any ideas? I am using VS 2008 Prof edition.

AQ

推荐答案

如果您使用的是System.Drawing,则可以创建相同大小的位图,然后使用SetPixel方法(或者,如果性能很重要, LockBits一个,请参见 Bitmap.Lockbits [
If you are using System.Drawing then you may create a bitmap of the same size then use the SetPixel method (or, if performance matters, the LockBits one, see Bitmap.Lockbits[^] at MSDN). The straighforward transformation of the RGBA components is the simple multiplication by 64 85 (sorry 64 was plainly wrong :-O, see SAKryukov reply), but you may choose alternatives.


第一条规则.不要使用GetPixel/SetPixel:太慢了!只有同时执行所有操作,您才能获得可接受的性能.

请执行下列操作.创建类System.Drawing.Bitmap的空位图,并使用System.Drawing.Bitmap.LockBits方法.对于pixelFormat,请使用System.Drawing.Imaging.PixelFormat.Format32bppPArgb(恰好是这一点,这是您的最低要求).填写2-2-2-2数据中每个像素的值.将每种颜色和不透明度的2位分量转换为8位,因此将最大值3映射为255:byte component8 = component2 * 85(原文如此!).

此页面上的代码示例将为您提供如何寻址像素和移动数据的想法:
First rule. Do not use GetPixel/SetPixel: it''s too slow! You can get acceptable performance only when you do it all at once.

Do the following. Create empty bitmap of the class System.Drawing.Bitmap and use System.Drawing.Bitmap.LockBits method. For pixelFormat, use System.Drawing.Imaging.PixelFormat.Format32bppPArgb (precisely this one, this is what you minimally need). Fill in the value of each pixel from your 2-2-2-2 data. Convert your 2-bit components for each color and opacity to 8-bit, so you maximum value of 3 is mapped to 255: byte component8 = component2 * 85 (sic!).

The code sample on this page will give you the idea how to address pixels and move data: http://msdn.microsoft.com/en-us/library/5ey6h79d(v=VS.100).aspx[^]. Pay attention for the use of System.Runtime.InteropServices.Marshal.

That should be enough to solve your problem.

—SA


这篇关于如何在C#中将原始二进制文件转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆