圖片下載

場景:用戶訪問外網服務器,外網服務器調用內網服務器的接口加載內網服務器上硬盤的圖片加載後返回給用戶。圖片路徑是保存在內網服務器上,經過外網服務器訪問不保存圖片到外網服務器的硬盤上,只是用二進制流把圖片返回,裏面有作壓縮處理算法

1:內網服務器(圖片保存在某一個硬盤上)服務器

   部署在內網服務器的代碼加密

      public dynamic GetPicture(string imgPath)code

orm

//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 "";
}ip

}部署

2:外網服務器(用的aspx)string

     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; } }

相關文章
相關標籤/搜索