1.环境:从另一台服务器上抓取tif 文件和图片,保存到本地服务器,其中tif 文件需要拆分成单个图片保存,tif文件是从ftp上得到的。
遇到的过的问题:
a.因都是网络图片,考虑的是在线抓取直接将流转化成图片,然后在保存图片.
关键代码:
if (url.StartsWith("http:") )|| url.StartsWith("ftp:"))
{
System.Net.WebRequest webreq = System.Net.WebRequest.Create(url);
System.Net.WebResponse webres = webreq.GetResponse();
Stream stream = webres.GetResponseStream();
img = Image.FromStream(stream);
stream.Close();
}
b.文件保存到本地后,读取文件使用的是Image.FromFile(path),此方法会占有文件,导致无法操作文件。
方案:根据下载后的本地地址先转化成数据流且仅只具有读取数据的权限,再创建图片
关键代码:
img = null;
string path = Download(baseUrl, ClaimNumber, url);
if (!string.IsNullOrEmpty(path))
{
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
int byteLength = (int)fileStream.Length;
byte[] fileBytes = new byte[byteLength];
fileStream.Read(fileBytes, 0, byteLength);
//文件流关閉,文件解除锁定
fileStream.Close();
img = Image.FromStream(new MemoryStream(fileBytes));
//img = Image.FromFile(path);//会占用文件
System.IO.File.Delete(path);//
}
c.tif 文件拆分成图片。
关键代码:
if (url.EndsWith("tif"))
{
Guid guid = (Guid)img.FrameDimensionsList.GetValue(0);
FrameDimension dimension = new FrameDimension(guid);
int totalPage = img.GetFrameCount(dimension);
string total = "共" + totalPage + "页";
for (int i = 0; i < totalPage; i++)
{
ExtClaimFilesInfo info = new ExtClaimFilesInfo();
info.ClaimNumber = ClaimNumber;
img.SelectActiveFrame(dimension, i);
string name = string.Format("{0}_{1}", ClaimNumber, i);
info.Path1 = UploadFile("claimData", name, dt, img);//原图,缩略图
info.VisitIndex = 1;
info.OpTime = DateTime.Now;
list.Add(info);
}
}
d.图片处理:本地保存缩略图和原图,若原图>500K 再压缩原图(j尽可能的保持原图清晰度)。
关键代码:
///
/// 原图大于500k 压缩图片
///
/// 原图图片路径
/// 压缩后图片路径
public bool OriginalNail(string path,string pathnew)
{
bool suc = false;
if (!string.IsNullOrEmpty(path))
{
try
{
if (File.Exists(pathnew))
{
File.Delete(pathnew);
}
FileInfo fi = new FileInfo(path);
Int64 len = fi.Length;//图片大小
decimal cnt = CHC.Common.Tools.CalcDivide(len, 1024);
if (cnt > 500)
{
CHC.Common.Picture.MakeThumbnail(path, pathnew, 1200, 120, "W");
fi.Delete();
}
else
{
fi.MoveTo(pathnew);
}
suc = true;
}
catch (Exception ex)
{
CHC.DAL.Log.Loger.Error(ex, "原图大于500k 压缩图片异常");
}
}
return suc;
}
2.具体代码:
a.生成缩略图 封装类:Picture
public class Picture
{
/**/
///
/// 生成缩略图
///
/// 源图路径(物理路径)
/// 缩略图路径(物理路径)
/// 缩略图宽度
/// 缩略图高度
/// 生成缩略图的方式
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
{
Image originalImage = Image.FromFile(originalImagePath);
MakeThumbnail(thumbnailPath, width, height, mode, originalImage);
}
public static void MakeThumbnail(string thumbnailPath, int width, int height, string mode, Stream stream)
{
Image originalImage = new Bitmap(stream);
MakeThumbnail(thumbnailPath, width, height, mode, originalImage);
}
private static void MakeThumbnail(string thumbnailPath, int width, int height, string mode, Image originalImage)
{
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
switch (mode)
{
case "HW"://指定高宽缩放(可能变形)
break;
case "W"://指定宽,高按比例
toheight = originalImage.Height * width / originalImage.Width;
break;
case "H"://指定高,宽按比例
towidth = originalImage.Width * height / originalImage.Height;
break;
case "Cut"://指定高宽裁减(不变形)
if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
{
oh = originalImage.Height;
ow = originalImage.Height * towidth / toheight;
y = 0;
x = (originalImage.Width - ow) / 2;
}
else
{
ow = originalImage.Width;
oh = originalImage.Width * height / towidth;
x = 0;
y = (originalImage.Height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (System.Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}
}
private string UploadFile(string folder,string name,DateTime? dt, Image img)
{
DateTime dt1 = dt.HasValue ? dt.Value : DateTime.Now;
//string baseUrl = System.Web.HttpContext.Current.Server.MapPath("~/");
string type1 = "original", type2 = "compress"; ;
//原型图路径
string customUrl = string.Format("\\upload\\{0}\\{1}\\{2}", folder, dt1.ToString("yyyyMMdd"), type1);
if (!System.IO.Directory.Exists(baseUrl + customUrl))
System.IO.Directory.CreateDirectory(baseUrl + customUrl);
string path = customUrl + "\\" + name + ".Jpeg";
string path1 = customUrl + "\\" + name+"tmp" + ".Jpeg";
string suoUrl = string.Format("\\upload\\{0}\\{1}\\{2}", folder, dt1.ToString("yyyyMMdd"), type2);
if (!System.IO.Directory.Exists(baseUrl + suoUrl))
System.IO.Directory.CreateDirectory(baseUrl + suoUrl);
string suopath = suoUrl + "\\" + name + ".Jpeg";
//原型图保存
img.Save(baseUrl + path1, System.Drawing.Imaging.ImageFormat.Jpeg);
OriginalNail(baseUrl + path1, baseUrl + path);
//缩略图
CHC.Common.Picture.MakeThumbnail(baseUrl + path, baseUrl + suopath, 120, 120, "Cut");
return suopath.Replace("\\", "/"); ;
}
///
/// 原图大于500k 压缩图片
///
/// 原图图片路径
/// 压缩后图片路径
public bool OriginalNail(string path,string pathnew)
{
bool suc = false;
if (!string.IsNullOrEmpty(path))
{
try
{
if (File.Exists(pathnew))
{
File.Delete(pathnew);
}
FileInfo fi = new FileInfo(path);
Int64 len = fi.Length;//图片大小
decimal cnt = CHC.Common.Tools.CalcDivide(len, 1024);
if (cnt > 500)
{
CHC.Common.Picture.MakeThumbnail(path, pathnew, 1200, 120, "W");
fi.Delete();
}
else
{
fi.MoveTo(pathnew);
}
suc = true;
}
catch (Exception ex)
{
CHC.DAL.Log.Loger.Error(ex, "原图大于500k 压缩图片异常");
}
}
return suc;
}
///
/// 实现ftp下载操作
///
/// 保存到本地的文件名
/// 远程文件名
public string Download(string filePath, string ClaimNumber, string url)
{
FtpWebRequest reqFTP;
//判断临时目录是否存在
if (!System.IO.Directory.Exists(filePath))
System.IO.Directory.CreateDirectory(filePath);
string str = string.Empty;
try
{
str = filePath + "\\" + ClaimNumber + ".tif";
reqFTP = (FtpWebRequest)FtpWebRequest.Create(url);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
//reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);//已放在url中
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
FileStream outputStream = new FileStream(str, FileMode.Create);
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
str = string.Empty;
CHC.DAL.Log.Loger.Log(ex, string.Format("保存tif文件到本地异常,url:{0},ClaimNumber:{1}", url, ClaimNumber));
}
return str;
}
e.最终调用方法:---tif文件下载 保存成图片,或图片保存
///
/// tif文件下载 保存成图片,或图片保存
///
///
public List Downtif(string url, string ClaimNumber,DateTime? dt)
{
List list = new List();
try
{
if (!string.IsNullOrEmpty(url))
{
Image img ;
if (url.StartsWith("http:") )//|| url.StartsWith("ftp:"))//网络图片,ftp 文件太大,先下载到本地
{
System.Net.WebRequest webreq = System.Net.WebRequest.Create(url);
System.Net.WebResponse webres = webreq.GetResponse();
Stream stream = webres.GetResponseStream();
img = Image.FromStream(stream);
stream.Close();
}
else if (url.StartsWith("ftp:"))
{
img = null;
string path = Download(baseUrl, ClaimNumber, url);
if (!string.IsNullOrEmpty(path))
{
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
int byteLength = (int)fileStream.Length;
byte[] fileBytes = new byte[byteLength];
fileStream.Read(fileBytes, 0, byteLength);
//文件流关閉,文件解除锁定
fileStream.Close();
img = Image.FromStream(new MemoryStream(fileBytes));
//img = Image.FromFile(path);//会占用文件
System.IO.File.Delete(path);//
}
}
else
{
img = Image.FromFile(url);//本地图片
}
if (img != null)
{
if (url.EndsWith("tif"))
{
Guid guid = (Guid)img.FrameDimensionsList.GetValue(0);
FrameDimension dimension = new FrameDimension(guid);
int totalPage = img.GetFrameCount(dimension);
string total = "共" + totalPage + "页";
for (int i = 0; i < totalPage; i++)
{
ExtClaimFilesInfo info = new ExtClaimFilesInfo();
info.ClaimNumber = ClaimNumber;
img.SelectActiveFrame(dimension, i);
string name = string.Format("{0}_{1}", ClaimNumber, i);
info.Path1 = UploadFile("claimData", name, dt, img);//原图,缩略图
info.VisitIndex = 1;
info.OpTime = DateTime.Now;
list.Add(info);
}
}
else
{
ExtClaimFilesInfo info = new ExtClaimFilesInfo();
info.ClaimNumber = ClaimNumber;
Random rad = new Random();
string _newname = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + rad.Next(100, 100000000).ToString();
string name = string.Format("{0}_{1}", ClaimNumber, _newname);
info.Path1 = UploadFile("claimData", name, dt, img);//原图,缩略图
info.VisitIndex = 1;
info.OpTime = DateTime.Now;
list.Add(info);
}
}
GC.Collect();
}
}
catch (Exception ex)
{
//throw ex;
CHC.DAL.Log.Loger.Log(ex, string.Format("图片下载异常,url:{0},ClaimNumber:{1}", url, ClaimNumber));
}
return list;
}