C# 操作文件字节时的图像转换
我有个问题。当图像保存在我的数据库中时,它们和filebytes一起保存,并且有一个指向此记录的引用ID。存在一个.ashx文件,该文件将获取此参考ID号并获取文件信息/文件字节,并显示图像或允许下载图像C# 操作文件字节时的图像转换,c#,image,C#,Image,我有个问题。当图像保存在我的数据库中时,它们和filebytes一起保存,并且有一个指向此记录的引用ID。存在一个.ashx文件,该文件将获取此参考ID号并获取文件信息/文件字节,并显示图像或允许下载图像 img src="/download.ashx?id=THEREFID 这将在页面上显示图像。如果我只是把一个链接到.ashx页面,它会下载图像。这很好。但是,我的一些图像保存为.TIF,我需要将它们转换为.jpeg 我有一个叫做FileData的类 public string FileNa
img src="/download.ashx?id=THEREFID
这将在页面上显示图像。如果我只是把一个链接到.ashx页面,它会下载图像。这很好。但是,我的一些图像保存为.TIF,我需要将它们转换为.jpeg
我有一个叫做FileData的类
public string FileName;
public byte[] theData;
public long FileSizeBytes;
public string MIME;
public string Extension;
在我的.ashx页面上,我有一个加载上述FileData类的方法。然后FileData类与HttpContext类一起被发送到一个方法:
private void Process(HttpContext context, FileData file)
{
context.Response.ContentTYpe = file.MIME;
context.Response.AddHeader("Content-Disposition", "attachment; filename="
+ file.FileName.Replace(' ', '_')
+ file.FileExtension);
context.Response.AddHeader("Content-Length", file.FileSizeBytes.ToString());
context.Response.Expires = 0;
context.Response.BinaryWrite(file.Data);
context.ApplicationInstance.CompleteRequest();
}
我需要找到一种方法将这些信息转换成jpeg格式。我在想可能是一个临时位图,将其转换为.jpeg,然后从中获取文件字节?我会按照您的意愿执行 差不多是这样的:
System.Drawing.Bitmap tiffImage;
using(BinaryWriter baseWriter = new BinaryWriter(new MemoryStream()))
{
baseWriter.Write(tiffData);
baseWriter.BaseStream.Position = 0;
tiffImage = new System.Drawing.Bitmap(baseWriter.BaseStream);
}
MemoryStream jpgStream = new MemoryStream();
tiffImage.Save(jpgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
jpgStream.Position = 0;
using (BinaryReader br = new BinaryReader(jpgStream))
{
context.Response.BinaryWrite(br.ReadBytes(jpgStream.Length));
}
我想出来了。以下是我所做的:
Image img = Image.FromStream(new MemoryStream(file.Data));
Bitmap bmp = (Bitmap)img;
EncoderParameters encoderParams = new EncoderParameters();
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 50L);
ImageCodecInfo codecInfo = GetEncoderInfo("image.jpeg");
MemoryStream newImage = new MemoryStream();
bmp.Save(newImage, codecInfo, encoderParams);
byte[] newData = newImage.ToArray();
//Overwritting the original FileData
file.Data = newData;
file.FileSizeBytes = newData.Length;
file.MIME = "image/jpeg";