C#如何实现图片的剪裁并保存
程序员文章站
2023-12-31 21:50:52
最近需要将一张图片上传并按指定位置剪裁,后来在网上找了一个剪裁图片的插件,但是只有前台没有后端,然后我各种百度,并最终完成,特此写一篇博客略表纪念。
前台我就不说了,用的...
最近需要将一张图片上传并按指定位置剪裁,后来在网上找了一个剪裁图片的插件,但是只有前台没有后端,然后我各种百度,并最终完成,特此写一篇博客略表纪念。
前台我就不说了,用的cropper插件,有兴趣的自己去百度找找吧。 有这个插件。
下面是代码:
httppostedfile file = context.request.files["avatar_file"]; string datasize = context.request.params["avatar_data"]; //{"x":30.003846153846148,"y":16.715384615384625,"height":300.8,"width":300.8,"rotate":0} 剪裁之后参数 javascriptserializer jss = new javascriptserializer(); imgsize imagesize = jss.deserialize<imgsize>(datasize); byte[] filebyte = setfiletobytearray(file);//图片数组 string strtextension = system.io.path.getextension(file.filename);//图片格式 memorystream ms1 = new memorystream(filebyte); bitmap sbitmap = (bitmap)image.fromstream(ms1); rectangle section = new rectangle(new point(imagesize.toint(imagesize.x), imagesize.toint(imagesize.y)), new size(imagesize.toint(imagesize.width), imagesize.toint(imagesize.height))); bitmap croppedimage = makethumbnailimage(sbitmap, section.width, section.height, section.width, section.height, section.x, section.y);
上面代码中用到我自己创建了一个imgsize类,代码如下:
class imgsize { //{"x":30.003846153846148,"y":16.715384615384625,"height":300.8,"width":300.8,"rotate":0} public double x { get; set; } public double y { get; set; } public double width { get; set; } public double height { get; set; } public int rotate { get; set; } public int toint(double doublevalue) { return convert.toint32(doublevalue); } }
上面代码中使用到的几个方法:
文件转化:
/// <summary> /// 将from表单file文件转化为byte数组 /// </summary> /// <param name="file">from提交文件流</param> /// <returns></returns> private byte[] setfiletobytearray(httppostedfile file) { stream stream = file.inputstream; byte[] ayyaybyte = new byte[file.contentlength]; stream.read(ayyaybyte, 0, file.contentlength); stream.close(); return ayyaybyte; }
核心剪裁方法:
/// <summary> /// 裁剪图片并保存 /// </summary> /// <param name="image">图片信息</param> /// <param name="maxwidth">缩略图宽度</param> /// <param name="maxheight">缩略图高度</param> /// <param name="cropwidth">裁剪宽度</param> /// <param name="cropheight">裁剪高度</param> /// <param name="x">x轴</param> /// <param name="y">y轴</param> public static bitmap makethumbnailimage(image originalimage, int maxwidth, int maxheight, int cropwidth, int cropheight, int x, int y) { bitmap b = new bitmap(cropwidth, cropheight); try { using (graphics g = graphics.fromimage(b)) { //清空画布并以透明背景色填充 g.clear(color.transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.drawimage(originalimage, new rectangle(0, 0, cropwidth, cropheight), x, y, cropwidth, cropheight, graphicsunit.pixel); image displayimage = new bitmap(b, maxwidth, maxheight); displayimage.save("e:\\cutimg.jpg", system.drawing.imaging.imageformat.jpeg); bitmap bit = new bitmap(b, maxwidth, maxheight); return bit; } } catch (system.exception e) { throw e; } finally { originalimage.dispose(); b.dispose(); } }
最后的结果是把存到了e盘根目录下面
以上所述是小编给大家介绍的c#如何实现图片的剪裁并保存,希望对大家有所帮助