我将图像保存到数据库,同时保持100%的质量。为了保持质量我使用以下方法。
public static byte[] ImageToByteArray(Image imageIn)
{
var qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
var encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
using (var msStream = new MemoryStream())
{
imageIn.Save(msStream, GetEncoderInfo("image/png"), encoderParams);
return msStream.ToArray();
}
}
使用处理程序并使用以下方法从db I&m 39中重新获取图像。
public void AddStampOnImage(Image img, HttpContext context)
{
Image modiFiedImage = GetScaledImage(img, resizeWidth, resizeHeight);
int width = modiFiedImage.Width;
int height = modiFiedImage.Height;
int compressionLevel = 100;
Image bitmapImg = new Bitmap(width, height, modiFiedImage.PixelFormat);
if (modiFiedImage.PixelFormat.ToString().Contains("Indexed"))
bitmapImg = new Bitmap(width, height, PixelFormat.Format24bppRgb);
PropertyItem[] propItems = img.PropertyItems;
foreach (var item in propItems)
{
PropertyItem pItem = img.GetPropertyItem(item.Id);
bitmapImg.SetPropertyItem(pItem);
}
Graphics oGraphic = Graphics.FromImage(bitmapImg);
oGraphic.CompositingQuality = CompositingQuality.HighQuality;
oGraphic.SmoothingMode = SmoothingMode.HighQuality;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
oGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
Rectangle oRectangle = new Rectangle(0, 0, width, height);
oGraphic.DrawImage(modiFiedImage, oRectangle);
int x;
int y;
Image watermarkImg = Image.FromFile(HttpContext.Current.Server.MapPath("~/images/" + watermarkimage + ""));
GetWatermarkPlacement(oGraphic.DpiX, oGraphic.DpiY, width, height, watermarkImg, out x, out y);
oGraphic.DrawImageUnscaled(watermarkImg, x, y);
oGraphic.Dispose();
watermarkImg.Dispose();
long[] quality = new long[1];
quality[0] = compressionLevel;
EncoderParameters encoderParams = new EncoderParameters();
EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
encoderParams.Param[0] = encoderParam;
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICI = null;
for (int i = 0; i < arrayICI.Length; i++)
{
if (arrayICI[i].FormatDescription.Equals("JPEG"))
{
jpegICI = arrayICI[i];
break;
}
}
SetImageCacheability(context);
bitmapImg.Save(context.Response.OutputStream, jpegICI, encoderParams);
encoderParam.Dispose();
}
这里的问题在某些情况下它工作正常意味着800kb图像可以在700-750kb中重新获得,但在某些情况下我保存了400kb图像并且它以800-1000kb图像重现。我不希望第二种情况发生。我在这里缺少什么?