当前位置: 首页 > 编程语言 > C#

为什么调整png图片大小后会失去透明度?分享

时间:2023-04-10 14:42:34 C#

为什么调整png图像的大小会失去其透明度?我正在尝试按如下方式调整图像大小。我将调整大小的图像返回到byte[],以便我可以将它存储在数据库中。png图像的透明度丢失。请帮助改善这一点。privatebyte[]GetThumbNail(stringimageFile,StreamimageStream,intimageLen){try{Image.GetThumbnailImageAbortimageCallBack=newImage.GetThumbnailImageAbort(ThumbnailCallback);位图getBitmap=newBitmap(imageFile);byte[]returnByte=newbyte[image;图片getThumbnail=getBitmap.GetThumbnailImage(160,59,imageCallBack,IntPtr.Zero);使用(Graphicsg=Graphics.FromImage(getThumbnail)){g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;g.DrawImage(getThumbnail,0,0,160,59);}使用(MemoryStreamms=newMemoryStream()){getThumbnail.Save(ms,ImageFormat.Png);获取缩略图。保存("test.png",ImageFormat.PNG);returnByte=ms.ToArray();}返回返回字节;}赶上(异常){抛出;你的代码没有按照你的想法去做......你使用GetThumbnailImage调整图像大小,然后将缩略图图像绘制到自身,这是毫无意义的。您可能在第一步中失去了透明度。相反,创建一个空白位图,并通过在空白位图上绘制来调整源图像的大小。privatebyte[]GetThumbNail(stringimageFile){try{byte[]结果;使用(图像缩略图=新位图(160、59)){使用(位图源=新位图(图像文件)){使用(图形g=图形。FromImage(缩略图)){g.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.抗锯齿;g.InterpolationMode=System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;g.DrawImage(来源,0,0,160,59);}}使用(MemoryStreamms=newMemoryStream()){thumbnail.Save(ms,ImageFormat.Png);thumbnail.Save("test.png",ImageFormat.Png);结果=ms.ToArray();}}返回结果;}赶上(异常){抛出;(我删除了一些从未用于与结果相关的任何参数,例如仅用于创建从未使用过的字节数组的imageLen参数。)Try.MakeTransparent()使用.MakeTransparent()调用图形对象。也许你应该,因为这个东西对我有用:以上是C#学习教程:为什么调整png图像的大小会失去其透明度?如果分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注——Stringpath=context.Server.MapPath("/images");如果(!path.EndsWith("\"))路径+="\";路径+=“none.png”;图片img=CreateThumbnail(Image.FromFile(path));MemoryStreamms=newMemoryStream();img.Save(ms,ImageFormat.Png);ms.WriteTo(context.Response.OutputStream);privateSystem.Drawing.ImageCreateThumbnail(System.Drawing.Imagei){intdWidth=i.Width;intdHeight=i.Height;intdMaxSize=150;如果(dWidth>dMaxSize){dHeight=(dHeight*dMaxSize)/dWidth;dWidth=dMaxSize;}if(dHeight>dMaxSize){dWidth=(dWidth*dMaxSize)/dHeight;dHeight=dMaxSize;}returni.GetThumbnailImage(dWidth,dHeight,delegate(){returnfalse;},IntPtr.Zero);}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: