如何根据IntPtr直接转换成.net里的System.Drawing.Image对象?

昵称这是个问题 2018-01-28 09:25:14
我用扫描仪,采用Twain协议方式,扫描后获取了一个IntPtr,如何把它转换为Image呢?求解,谢谢!
...全文
1322 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
全栈极简 2018-01-29
  • 打赏
  • 举报
回复
我记得codeproject上面有完整的可应用的程序的,可以找找看。
全栈极简 2018-01-29
  • 打赏
  • 举报
回复
   IntPtr bmpptr = GlobalLock(img);
                            IntPtr pixptr = GetPixelInfo(bmpptr);
                            Bitmap bitmap = BitmapFromDIB(bmpptr, pixptr);
 [DllImport("kernel32.dll", ExactSpelling = true)]
        internal static extern IntPtr GlobalLock(IntPtr handle);
/// <summary>
        /// 获得内存图片像素信息
        /// </summary>
        /// <param name="bmpptr">内存图片指针</param>
        /// <returns></returns>
        protected IntPtr GetPixelInfo(IntPtr bmpptr)
        {
            BITMAPINFOHEADER bmi = new BITMAPINFOHEADER();
            Marshal.PtrToStructure(bmpptr, bmi);
            Rectangle bmprect = new Rectangle(0, 0, 0, 0); ;
            bmprect.X = bmprect.Y = 0;
            bmprect.Width = bmi.biWidth;
            bmprect.Height = bmi.biHeight;

            if (bmi.biSizeImage == 0)
                bmi.biSizeImage = ((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight;

            int p = bmi.biClrUsed;
            if ((p == 0) && (bmi.biBitCount <= 8))
                p = 1 << bmi.biBitCount;
            p = (p * 4) + bmi.biSize + (int)bmpptr;
            return (IntPtr)p;
        }
/// <summary>
        /// 从DIB获得图片指针
        /// </summary>
        /// <param name="pDIB"></param>
        /// <param name="pPix"></param>
        /// <returns></returns>
        public static Bitmap BitmapFromDIB(IntPtr pDIB, IntPtr pPix)
        {
            MethodInfo mi = typeof(Bitmap).GetMethod("FromGDIplus",
                            BindingFlags.Static | BindingFlags.NonPublic);

            if (mi == null)
                return null; // (permission problem) 

            IntPtr pBmp = IntPtr.Zero;
            int status = GdipCreateBitmapFromGdiDib(pDIB, pPix, out pBmp);

            if ((status == 0) && (pBmp != IntPtr.Zero)) // success 
                return (Bitmap)mi.Invoke(null, new object[] { pBmp });
            else
                return null; // failure 
        }
在ASP.NET中上传图片并生成缩略图的C#源码 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.IO; using System.Drawing.Imaging; namespace eMeng.Exam { /// /// Thumbnail 的摘要说明。 /// public class Thumbnail : System.Web.UI.Page { protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Button Button1; private void Page_Load(object sender, System.EventArgs e) { // 在此处放置用户代码以初始化页面 Label1.Text = "

在ASP.NET轻松实炙趼酝?lt;/h3>"; Button1.Text = "上载并显示缩略图"; } #region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) { // // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。 // InitializeComponent(); base.OnInit(e); } /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { this.Button1.Click += new System.EventHandler(this.Button1_Click); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void Button1_Click(object sender, System.EventArgs e) { HttpFileCollection MyFileColl = HttpContext.Current.Request.Files; HttpPostedFile MyPostedFile = MyFileColl[0]; if (MyPostedFile.ContentType.ToString().ToLower().IndexOf("image") < 0) { Response.Write("无效的图形格式。"); return; } GetThumbNail(MyPostedFile.FileName, 100, 100, MyPostedFile.ContentType.ToString(), false, MyPostedFile.InputStream); } private System.Drawing.Imaging.ImageFormat GetImageType(object strContentType) { if ((strContentType.ToString().ToLower()) == "image/pjpeg") { return System.Drawing.Imaging.ImageFormat.Jpeg; } else if ((strContentType.ToString().ToLower()) == "image/gif") { return System.Drawing.Imaging.ImageFormat.Gif; } else if ((strContentType.ToString().ToLower()) == "image/bmp") { return System.Drawing.Imaging.ImageFormat.Bmp; } else if ((strContentType.ToString().ToLower()) == "image/tiff") { return System.Drawing.Imaging.ImageFormat.Tiff; } else if ((strContentType.ToString().ToLower()) == "image/x-icon") { return System.Drawing.Imaging.ImageFormat.Icon; } else if ((strContentType.ToString().ToLower()) == "image/x-png") { return System.Drawing.Imaging.ImageFormat.Png; } else if ((strContentType.ToString().ToLower()) == "image/x-emf") { return System.Drawing.Imaging.ImageFormat.Emf; } else if ((strContentType.ToString().ToLower()) == "image/x-exif") { return System.Drawing.Imaging.ImageFormat.Exif; } else if ((strContentType.ToString().ToLower()) == "image/x-wmf") { return System.Drawing.Imaging.ImageFormat.Wmf; } else { return System.Drawing.Imaging.ImageFormat.MemoryBmp; } } private void GetThumbNail(string strFileName, int iWidth, int iheight, string strContentType, bool blnGetFromFile, System.IO.Stream ImgStream) { System.Drawing.Image oImg; if (blnGetFromFile) { oImg = System.Drawing.Image.FromFile(strFileName); } else { oImg = System.Drawing.Image.FromStream(ImgStream); } oImg = oImg.GetThumbnailImage(iWidth, iheight, null, IntPtr.Zero); string strGuid = System.Guid.NewGuid().ToString().ToUpper(); string strFileExt = strFileName.Substring(strFileName.LastIndexOf(".")); Response.ContentType = strContentType; MemoryStream MemStream = new MemoryStream(); oImg.Save(MemStream, GetImageType(strContentType)); MemStream.WriteTo(Response.OutputStream); } } } 功能: 1。把图片文件(JPG GIF PNG)上传, 2。保存到指定的路径(在web.config中设置路径,以文件的原有格式保存), 3。并自动生成指定宽度的(在web.config中设置宽度) 4。和指定格式的(在web.config中指定缩略图的格式) 5。和原图比例相同的缩略图(根据宽度和原图的宽和高计算所略图的高度) 6。可以判断是否已经存在文件 7。如果不覆盖,则给出错误 8。如果选中"覆盖原图"checkbox,则覆盖原图。 9。可以根据要求,在webform上设置1个以上的file input和相应的checkbox 10。并在文件上传完毕后,显示原图的文件名,尺寸,字节,和 11。缩略图的文件名尺寸。 12。缩略图的文件名格式:原图+"_thumb."+指定格式,如:test.jpg_thumb.gif,以便于管理。 -------------------- public void UploadFile(object sender, System.EventArgs e) { string imgNameOnly, imgNameNoExt, imgExt; string imgThumbnail; int erroNumber = 0; System.Drawing.Image oriImg, newImg; string strFePicSavePath = ConfigurationSettings.AppSettings["FePicSavePath"].ToString(); string strFePicThumbFormat = ConfigurationSettings.AppSettings["FePicThumbFormat"].ToString().ToLower(); int intFeThumbWidth = Int32.Parse(ConfigurationSettings.AppSettings["FePicThumbWidth"]); string fileExt; StringBuilder picInfo = new StringBuilder(); if(Page.IsValid) { for(int i = 0;i < Request.Files.Count; i++) { HttpPostedFile PostedFile = Request.Files[i]; fileExt = (System.IO.Path.GetExtension(PostedFile.FileName)).ToString().ToLower(); imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName); if(fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".png") { if(System.IO.File.Exists(strFePicSavePath + imgNameOnly) && (checkboxlistRewrite.Items[i].Selected == false)) { erroNumber = erroNumber + 1; picInfo.Append("错误:文件("+ (i+1) +") " + imgNameOnly + " 已经存在,请修改文件名
" ); } } else { erroNumber = erroNumber + 1; picInfo.Append("错误:文件("+ (i+1) +") " + imgNameOnly + " 扩展名 " + fileExt + " 不被许可
" ); } } if(erroNumber > 0) { picInfo.Append("全部操作均未完成,请修改错误,再进行操作
"); } else { for(int i = 0;i < Request.Files.Count; i++) { HttpPostedFile PostedFile = Request.Files[i]; imgNameOnly = System.IO.Path.GetFileName(PostedFile.FileName); imgNameNoExt = System.IO.Path.GetFileNameWithoutExtension(PostedFile.FileName); imgExt = System.IO.Path.GetExtension(PostedFile.FileName).ToString().ToLower(); oriImg = System.Drawing.Image.FromStream(PostedFile.InputStream); newImg = oriImg.GetThumbnailImage(intFeThumbWidth, intFeThumbWidth * oriImg.Height/oriImg.Width,null,new System.IntPtr(0)); switch(imgExt) { //case ".jpeg": case ".jpg": oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Jpeg); break; case ".gif": oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Gif); break; case ".png": oriImg.Save(strFePicSavePath + imgNameOnly , System.Drawing.Imaging.ImageFormat.Png); break; } //oriImg.Save(ConfigurationSettings.AppSettings["FePicSavePath"] + imgNameNoExt + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); switch(strFePicThumbFormat) { //jpeg format can get the smallest file size, and the png is the largest size //case "jpeg": case "jpg": newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg); imgThumbnail = imgNameOnly + "_thumb.jpg"; break; case "gif": newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.gif",System.Drawing.Imaging.ImageFormat.Gif); imgThumbnail = imgNameOnly + "_thumb.gif"; break; case "png": newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.png",System.Drawing.Imaging.ImageFormat.Png); imgThumbnail = imgNameOnly + "_thumb.png"; break; default: newImg.Save(strFePicSavePath + imgNameOnly + "_thumb.jpg",System.Drawing.Imaging.ImageFormat.Jpeg); imgThumbnail = imgNameOnly + "_thumb.jpg"; break; }//switch picInfo.Append("文件 名:" + imgNameOnly + " ( " + oriImg.Width + " x " + oriImg.Height + " ) " + PostedFile.ContentLength/1024 + "KB
"); picInfo.Append("缩略图名:" + imgThumbnail + " ( " + newImg.Width + " x " + newImg.Height + " )

"); oriImg.Dispose(); newImg.Dispose(); }//for picInfo.Append("所有操作成功
"); }// if erronumber = 0 } else { picInfo.Append("有错误,请检查。操作未成功
"); } lblPicInfo.Text = picInfo.ToString(); }
资料引用:http://www.knowsky.com/5723.html

Example002-渐显的窗体 Example003-使程序始终在前面 Example004-将窗体编译成类库 Example005-继承窗体的设计 Example006-设计多边形窗体 Example007-用获取路径的方法得到圆形窗体 Example008-分割窗体 Example009-在菜单中加入图标 Example010-渐变的窗口背景 Example011-使用任务栏的状态区 Example012-在运行时更新状态栏信息 Example013-无标题窗体的拖动 Example014-设置应用程序的图标 Example015-共享菜单项 Example016-动态设置窗体的光标 Example017-自己绘制菜单 Example018-向窗体的系统菜单添加菜单项 namespace Example018_向窗体的系统菜单添加菜单项 { /// /// Form1 的摘要说明。 /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; /// /// 必需的设计器变量。 /// private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); // // mainMenu1 // this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1}); // // menuItem1 // this.menuItem1.Index = 0; this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem2}); this.menuItem1.Text = "File"; // // menuItem2 // this.menuItem2.Index = 0; this.menuItem2.Text = "Exit"; this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(292, 273); this.Menu = this.mainMenu1; this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); } #endregion /// /// 应用程序的主入口点。 /// [STAThread] [System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr GetSystemMenu(IntPtr hwnd,bool bRevert); [System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr AppendMenu(IntPtr hMenu,int wFlags,IntPtr wIDNewItem,string lpNewItem); const int MF_POPUP = 0x0010; const int MF_SEPARATOR = 0x0800; static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { IntPtr mnuSystem; mnuSystem=GetSystemMenu(this.Handle,false); AppendMenu(mnuSystem, MF_SEPARATOR, (IntPtr)0, ""); for(int i= 0;i /// Form1 的摘要说明。 /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Button button1; /// /// 必需的设计器变量。 /// private System.ComponentModel.Container components = null; public Form1() { // // Windows 窗体设计器支持所必需的 // Thread.CurrentThread.CurrentUICulture=new CultureInfo("zh-cn"); InitializeComponent(); // // TODO: 在 InitializeComponent 调用后添加任何构造函数代码 // } /// /// 清理所有正在使用的资源。 /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1)); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.AccessibleDescription = ((string)(resources.GetObject("button1.AccessibleDescription"))); this.button1.AccessibleName = ((string)(resources.GetObject("button1.AccessibleName"))); this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("button1.Anchor"))); this.button1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("button1.BackgroundImage"))); this.button1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("button1.Dock"))); this.button1.Enabled = ((bool)(resources.GetObject("button1.Enabled"))); this.button1.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("button1.FlatStyle"))); this.button1.Font = ((System.Drawing.Font)(resources.GetObject("button1.Font"))); this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image"))); this.button1.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("button1.ImageAlign"))); this.button1.ImageIndex = ((int)(resources.GetObject("button1.ImageIndex"))); this.button1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("button1.ImeMode"))); this.button1.Location = ((System.Drawing.Point)(resources.GetObject("button1.Location"))); this.button1.Name = "button1"; this.button1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("button1.RightToLeft"))); this.button1.Size = ((System.Drawing.Size)(resources.GetObject("button1.Size"))); this.button1.TabIndex = ((int)(resources.GetObject("button1.TabIndex"))); this.button1.Text = resources.GetString("button1.Text"); this.button1.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("button1.TextAlign"))); this.button1.Visible = ((bool)(resources.GetObject("button1.Visible"))); // // Form1 // this.AccessibleDescription = ((string)(resources.GetObject("$this.AccessibleDescription"))); this.AccessibleName = ((string)(resources.GetObject("$this.AccessibleName"))); this.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("$this.Anchor"))); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button1}); this.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("$this.Dock"))); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "Form1"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.Visible = ((bool)(resources.GetObject("$this.Visible"))); this.ResumeLayout(false); } #endregion /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.Run(new Form1()); } } }
基于C#的典型图像处理算法 第二章: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; //using System.Drawing.Drawing2D; namespace gray { public partial class Form1 : Form { public Form1() { InitializeComponent(); myTimer = new HiPerfTimer(); } private void open_Click(object sender, EventArgs e) { OpenFileDialog opnDlg = new OpenFileDialog(); opnDlg.Filter = "所有图像文件 | *.bmp; *.pcx; *.png; *.jpg; *.gif;"+ "*.tif; *.ico; *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf|" + "位图( *.bmp; *.jpg; *.png;...) | *.bmp; *.pcx; *.png; *.jpg; *.gif; *.tif; *.ico|" + "矢量图( *.wmf; *.eps; *.emf;...) | *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf"; opnDlg.Title = "打开图像文件"; opnDlg.ShowHelp = true; if (opnDlg.ShowDialog() == DialogResult.OK) { curFileName = opnDlg.FileName; try { curBitmap = (Bitmap)Image.FromFile(curFileName); } catch (Exception exp) { MessageBox.Show(exp.Message); } } Invalidate(); } private void save_Click(object sender, EventArgs e) { if(curBitmap == null) { return; } SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.Title = "保存为"; saveDlg.OverwritePrompt = true; saveDlg.Filter = "BMP文件 (*.bmp) | *.bmp|" + "Gif文件 (*.gif) | *.gif|" + "JPEG文件 (*.jpg) | *.jpg|" + "PNG文件 (*.png) | *.png"; saveDlg.ShowHelp = true; if(saveDlg.ShowDialog() == DialogResult.OK) { string fileName = sav

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

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