前言
图片的放大与缩小功能是我们日常系统中经常看到的一种功能,但是现在大部分的图片放大缩小功能都是前端实现的,也就是用js来控制img的高和宽来实现图片的放大和缩小功能,今天我们就用C#实现一种从后端来放大图片的功能。
代码如下:
public Bitmap Magnifier(Bitmap srcbitmap, int multiple) { if (multiple <= 0) { multiple = 0; return srcbitmap; } Bitmap bitmap = new Bitmap(srcbitmap.Size.Width * multiple, srcbitmap.Size.Height * multiple); System.Drawing.Imaging.BitmapData srcbitmapdata = srcbitmap.LockBits(new Rectangle(new Point(0, 0), srcbitmap.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Imaging.BitmapData bitmapdata = bitmap.LockBits(new Rectangle(new Point(0, 0), bitmap.Size), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); unsafe { byte* srcbyte = (byte*)(srcbitmapdata.Scan0.ToPointer()); byte* sourcebyte = (byte*)(bitmapdata.Scan0.ToPointer()); for (int y = 0; y < bitmapdata.Height; y++) { for (int x = 0; x < bitmapdata.Width; x++) { long index = (x / multiple) * 4 + (y / multiple) * srcbitmapdata.Stride; sourcebyte[0] = srcbyte[index]; sourcebyte[1] = srcbyte[index + 1]; sourcebyte[2] = srcbyte[index + 2]; sourcebyte[3] = srcbyte[index + 3]; sourcebyte += 4; } } } srcbitmap.UnlockBits(srcbitmapdata); bitmap.UnlockBits(bitmapdata); return bitmap; }总结:
以上就是用C#实现的图片按倍数放大的功能,主要用到了Bitmap类来生成新的放大的图片,大家可以参考一下,若大家有更好的方法和思路欢迎在评论区留言讨论。