利用C#代码实现图片旋转360度
程序员文章站
2022-06-22 16:02:34
using system;
using system.collections.generic;
using system.drawing;
using sys...
using system; using system.collections.generic; using system.drawing; using system.io; using system.linq; using system.text; namespace 图片旋转程序 { public class imagehelper { /// <summary> /// 以逆时针为方向对图像进行旋转 /// </summary> /// <param name="b">位图流</param> /// <param name="angle">旋转角度[0,360](前台给的)</param> /// <returns></returns> public image rotateimg(image b, int angle, string file) { angle = angle % 360; //弧度转换 double radian = angle * math.pi / 180.0; double cos = math.cos(radian); double sin = math.sin(radian); //原图的宽和高 int w = b.width; int h = b.height; int w = (int)(math.max(math.abs(w * cos - h * sin), math.abs(w * cos + h * sin))); int h = (int)(math.max(math.abs(w * sin - h * cos), math.abs(w * sin + h * cos))); //目标位图 bitmap dsimage = new bitmap(w, h); system.drawing.graphics g = system.drawing.graphics.fromimage(dsimage); g.interpolationmode = system.drawing.drawing2d.interpolationmode.bilinear; g.smoothingmode = system.drawing.drawing2d.smoothingmode.highquality; //计算偏移量 point offset = new point((w - w) / 2, (h - h) / 2); //构造图像显示区域:让图像的中心与窗口的中心点一致 rectangle rect = new rectangle(offset.x, offset.y, w, h); point center = new point(rect.x + rect.width / 2, rect.y + rect.height / 2); g.translatetransform(center.x, center.y); g.rotatetransform(angle); //恢复图像在水平和垂直方向的平移 g.translatetransform(-center.x, -center.y); g.drawimage(b, rect); //重至绘图的所有变换 g.resettransform(); g.save(); g.dispose(); //保存旋转后的图片 dsimage.save(@"d:\img\" + path.getfilenamewithoutextension(file) + "\\" + angle + ".png", system.drawing.imaging.imageformat.png); return dsimage; } public image rotateimg(string filename, int angle, string file) { return rotateimg(getsourceimg(filename), angle, file); } public image getsourceimg(string filename) { image img; img = bitmap.fromfile(filename); return img; } } class program { static void main(string[] args) { string[] strarr = directory.getfiles(@"d:\img"); foreach (string file in strarr) { console.writeline(file); //输出e:\123\新建文本文件.txt console.writeline(path.getfilenamewithoutextension(file)); //如果要保存的目录不存在,则先创建 if (!directory.exists(@"d:\img\" + path.getfilenamewithoutextension(file))) { directory.createdirectory(@"d:\img\" + path.getfilenamewithoutextension(file)); } filestream fs = new filestream(file, filemode.open, fileaccess.read); image img = bitmap.fromstream(fs); imagehelper ih = new imagehelper(); for (int i = 1; i <= 360; i++) { ih.rotateimg(img, i, file); } fs.close(); } console.readkey(); } } }
以上所述是本文的全部内容,有问题的可以和小编联系,谢谢对的支持!
上一篇: 车联网时代,加油也无需去加油站