高校手机签到系统——zxing.net生成二维码(补充)
高校手机签到系统——第一部分Authority权限系统(上)
高校手机签到系统——第一部分Authority权限系统(下)
关于zxing.net的使用网上已有很多说明,可是在mvc模式下,怎么保存生成的图片返回链接?
使用zxing生成bitmap:
BarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Width = 400, Height = 400 } }; string time = DateTime.Now.ToString(); Bitmap bitmap = writer.Write(id + "|" + time);
此bitmap有一save方法Image.Save (String, ImageCodecInfo, EncoderParameters),参数分别是路径,编码器,以及编码器参数。
初始化编码器ImageCodecInfo imageCodecInfo = (from e in ImageCodecInfo.GetImageEncoders() where e.MimeType == "image/jpeg" select e).First();
初始化编码器参数EncoderParameters encoderParameters = new EncoderParameters(1);
EncoderParameter encoderParameter = new EncoderParameter(Encoder.Quality, 75L);
接下来保存到相应的路径即可。完整的代码:
public ActionResult LoadQrcode(string id) { BarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Width = 400, Height = 400 } }; string time = DateTime.Now.ToString(); Bitmap bitmap = writer.Write(id + "|" + time); ImageCodecInfo imageCodecInfo = (from e in ImageCodecInfo.GetImageEncoders() where e.MimeType == "image/jpeg" select e).First(); EncoderParameters encoderParameters = new EncoderParameters(1); EncoderParameter encoderParameter = new EncoderParameter(Encoder.Quality, 75L); encoderParameters.Param[0] = encoderParameter; if (Directory.Exists(Server.MapPath("/Images/" + id + "/"))) { FileInfo[] files = new DirectoryInfo(Server.MapPath("/Images/" + id + "/")).GetFiles(); foreach (FileInfo fi in files) System.IO.File.Delete(Path.Combine(Server.MapPath("/Images/" + id + "/"), fi.Name)); } else Directory.CreateDirectory(Server.MapPath("/Images/" + id + "/")); bitmap.Save(Path.Combine(Server.MapPath("/Images/" + id + "/"), DateTime.Now.Date.ToFileTimeUtc()+ ".jpeg"), imageCodecInfo, encoderParameters); return Json("/Images/" + id + "/" + DateTime.Now.Date.ToFileTimeUtc() + ".jpeg", JsonRequestBehavior.AllowGet); }