图片下载

mac2025-08-10  9

场景:用户访问外网服务器,外网服务器调用内网服务器的接口加载内网服务器上硬盘的图片加载后返回给用户。图片路径是保存在内网服务器上,通过外网服务器访问不保存图片到外网服务器的硬盘上,只是用二进制流把图片返回,里面有做压缩处理

1:内网服务器(图片保存在某一个硬盘上)

   部署在内网服务器的代码

      public dynamic GetPicture(string imgPath)

//imgPath为图片的绝对路径

 string path=Houdar.Core.Util.Common.DESTool.DecryptDES(imgPath);

try { FileStream fs = new FileStream(path, FileMode.Open); byte[] byData = new byte[fs.Length]; fs.Read(byData, 0, byData.Length); fs.Close(); string res = Convert.ToBase64String(byData);  return res; } catch (Exception ex) { return ""; }

}

2:外网服务器(用的aspx)

     ashx代码:

       

void GetPicture(HttpContext context) { string imgPath = context.Request.Params["imgPath"] == "" ? "" : context.Request.Params["imgPath"];  //加密后的图片路径 imgPath = imgPath.Replace(' ', '+');    //特殊字符可用其它方法处理,这里先简单写上 dynamic res = PrescriptionBLL.GetPicture(imgPath); byte[] ImgByte = Convert.FromBase64String(res);

MemoryStream ms1 = new MemoryStream(ImgByte); Bitmap img = (Bitmap)Image.FromStream(ms1); ms1.Close();

byte[] newImg = null; if (!img.Equals(null)) { var height = img.Height / 2; var width = img.Width / 2;

var bitmap = ChangeImgSize(img, new Size(width,height)); newImg = YaSuo(bitmap, 70); }

context.Response.ContentType = "image/jpeg"; context.Response.BinaryWrite(newImg); }

   

Bitmap ChangeImgSize(Bitmap img, Size newSize) { Bitmap newImg = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb); Graphics gDraw = Graphics.FromImage(newImg); // 插值算法的质量  gDraw.InterpolationMode = InterpolationMode.HighQualityBicubic; gDraw.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel); return newImg; }

byte[] YaSuo(Image iSource, int flag) { byte[] bt = null; ImageFormat tFormat = iSource.RawFormat; EncoderParameters ep = new EncoderParameters();

long[] qy = new long[1]; qy[0] = flag;

EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } return ImageToByteArr(iSource); } catch { return bt; } }

 

byte[] ImageToByteArr(Image img) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; byte[] imageBytes = new byte[ms.Length]; ms.Read(imageBytes, 0, imageBytes.Length); return imageBytes; } }

最新回复(0)