C# WebAPi接收和发送图片
先上一个准备代码:image和字节数组相互转换:
//字节数组转image //pic是字节数组 System.IO.MemoryStream ms = new System.IO.MemoryStream(pic); System.Drawing.Image image = System.Drawing.Image.FromStream(ms); //image转字节数组 MemoryStream newms = new MemoryStream(); image.Save(newms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] BPicture = new byte[newms.Length]; BPicture = newms.GetBuffer();
现在介入正题,我们这个字节数组哪里来的呢?要么是从服务器的文件系统中拉的,要么是从数据库里拉的,这边不介绍前者,介绍一下后者。我使用的数据库是Oracle,这边 PAT_PIC字段是Oracle的blob类型,
先写get方法:
public string GetPatientPicByHemoId(string hemoId) { string result = string.Empty; PatientModel.MED_PATIENTS_PICDataTable dtPic = _patientService.GetPatientPicByHemoId(hemoId); if (dtPic != null && dtPic.Rows.Count > 0) { byte[] pic = dtPic[0].PAT_PIC; result = Convert.ToBase64String(pic); } eturn result.Length > 0 ? Utility.StringToJsonBySuccess(result, true) : Utility.StringToJsonBySuccess(result, false); }
然后写下save方法:
[HttpPost] [Route("Api/MedPatient/UploadInternalPhoto")] public async Task<string> UploadInternalPhoto() { int result = 0; string message = string.Empty; bool success = false; try { Logger.Info("开始调用UploadPatientPhoto..."); string filePath = "~\\UploadFiles\\Photo"; string dir = HttpContext.Current.Server.MapPath(filePath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); if (!Request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string fileFullName = string.Empty; var provider = new CustomMultipartFormDataStreamProvider(dir); await Request.Content.ReadAsMultipartAsync(provider); string hemoId = provider.FormData.Get("hemoId"); MultipartFileData file = provider.FileData.FirstOrDefault(); if (file != null) { fileFullName = dir + file.LocalFileName.Substring(file.LocalFileName.LastIndexOf("\\")); } var imageCodecInfoList = ImageCodecInfo.GetImageEncoders(); string mimeType = "image/jpeg"; ImageCodecInfo myImageCodec = null; foreach (var imgCodec in imageCodecInfoList) { if (imgCodec.MimeType == mimeType) { myImageCodec = imgCodec; break; } } if (myImageCodec == null) return null; EncoderParameters encoderParams = new EncoderParameters(1); System.Drawing.Imaging.Encoder myCompressQuanlityEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameter myCompressQualityParam = new EncoderParameter(myCompressQuanlityEncoder, 80L); encoderParams.Param[0] = myCompressQualityParam; byte[] tempImage; using (Bitmap bmpPic = new Bitmap(fileFullName)) { using (MemoryStream msPicture = new MemoryStream()) { bmpPic.Save(msPicture, myImageCodec, encoderParams); tempImage = msPicture.ToArray(); } } InternalModel.MED_INTERNAL_PICDataTable pic = _internal.GetInternalPic(hemoId); if (pic != null && pic.Rows.Count > 0) { pic[0].PAT_PIC = tempImage; } else { var row = pic.NewMED_INTERNAL_PICRow(); row.HEMOID = hemoId; row.PAT_PIC = tempImage; pic.AddMED_INTERNAL_PICRow(row); } result = _internal.SaveInternalPic(pic); success = true; } catch (Exception ex) { message = ex.Message; Logger.Error("上传患者照片失败", ex); } return Utility.StringToJsonBySuccess(message, success); }
以下是StringToJsonBySuccess方法
/// <summary>
/// 字符串转换成Json带是否成功标记
/// </summary>
/// <param name="result"></param>
/// <param name="success"></param>
/// <returns></returns>
public static string StringToJsonBySuccess(string result, bool success) { if (success) { result = "{\"SUCCESS\":\"TRUE\",\"DATA\":\"" + result + "\"}"; } else { result = "{\"SUCCESS\":\"FALSE\"}"; } return result; }
好了!明天国庆节提前回家喽~