栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将访问图像OLE对象转换为C#中的原始图像字节数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将访问图像OLE对象转换为C#中的原始图像字节数组

这里的问题是,嵌入的图像不是简单的

BMP
JPEG
。那是个

Microsoft Word Picture

并且OLE标头信息比原始

GetImageBytesFromOLEField()
代码的300字节窗口大得多。(也就是说,在扫描300个字节后,它只是放弃了“无法确定标头大小…”。)

以下是该代码在其自己的类中的更新版本。课程测试包括提供的

Microsoft Word Picture
,简单的
BMP
和简单的
JPEG

using System;using System.Collections.Generic;using System.Linq;namespace OleImageTest{    public static class OleImageUnwrap    {        public static byte[] GetImageBytesFromOLEField(byte[] oleFieldBytes)        { // adapted from http://blogs.msdn.com/b/pranab/archive/2008/07/15/removing-ole-header-from-images-stored-in-ms-access-db-as-ole-object.aspx const int maxNumberOfBytesToSearch = 10000; byte[] imageBytes;  // return value var imageSignatures = new List<byte[]>(); // PNG_ID_BLOCK = "x89PNGrnx1an" imageSignatures.Add(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }); // JPG_ID_BLOCK = "xFFxD8xFF" imageSignatures.Add(new byte[] { 0xFF, 0xD8, 0xFF }); // GIF_ID_BLOCK = "GIF8" imageSignatures.Add(new byte[] { 0x47, 0x49, 0x46, 0x38 }); // TIFF_ID_BLOCK = "II*x00" imageSignatures.Add(new byte[] { 0x49, 0x49, 0x2A, 0x00 }); // BITMAP_ID_BLOCK = "BM" imageSignatures.Add(new byte[] { 0x42, 0x4D }); int numberOfBytesToSearch = (oleFieldBytes.Count() < maxNumberOfBytesToSearch ? oleFieldBytes.Count() : maxNumberOfBytesToSearch); var startingBytes = new byte[numberOfBytesToSearch]; Array.Copy(oleFieldBytes, startingBytes, numberOfBytesToSearch); var positions = new List<int>(); foreach (byte[] blockSignature in imageSignatures) {     positions = startingBytes.IndexOfSequence(blockSignature, 0);     if (positions.Count > 0)     {         break;     } } int iPos = -1; if (positions.Count > 0) {     iPos = positions[0]; } if (iPos == -1)     throw new Exception("Unable to determine header size for the OLE Object"); imageBytes = new byte[oleFieldBytes.LongLength - iPos]; System.IO.MemoryStream ms = new System.IO.MemoryStream(); ms.Write(oleFieldBytes, iPos, oleFieldBytes.Length - iPos); imageBytes = ms.ToArray(); ms.Close(); ms.Dispose(); return imageBytes;        }        private static List<int> IndexOfSequence(this byte[] buffer, byte[] pattern, int startIndex)        { // ref: http://stackoverflow.com/a/332667/2144390 List<int> positions = new List<int>(); int i = Array.IndexOf<byte>(buffer, pattern[0], startIndex); while (i >= 0 && i <= buffer.Length - pattern.Length) {     byte[] segment = new byte[pattern.Length];     Buffer.BlockCopy(buffer, i, segment, 0, pattern.Length);     if (segment.SequenceEqual<byte>(pattern))         positions.Add(i);     i = Array.IndexOf<byte>(buffer, pattern[0], i + 1); } return positions;        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408409.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号