【发布时间】:2012-11-02 12:52:57
【问题描述】:
我有一个 c# 程序,它打开一个 .tif 图像,然后提供保存它的选项。但是,保存图像时质量总是会下降。
(编辑:我在保存图像时传递了一些参数,以便质量为 100% 并且没有压缩,但实际唯一颜色的数量从 254 变为 16,即使图像属性显示 8bpp)
(EDIT2:有问题的图像是每像素 8 位的灰度图像 - 256 种颜色/灰度 - 这不会发生在我测试的每像素 24 位彩色图像中所有颜色都保留了。我开始认为图像类可能只支持16种灰度)
如何避免这种情况?
打开图片的代码如下:
public Image imageImport()
{
Stream myStream = null;
OpenFileDialog openTifDialog = new OpenFileDialog();
openTifDialog.Title = "Open Desired Image";
openTifDialog.InitialDirectory = @"c:\";
openTifDialog.Filter = "Tiff only (*.tif)|*.tif";
openTifDialog.FilterIndex = 1;
openTifDialog.RestoreDirectory = true;
if (openTifDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openTifDialog.OpenFile()) != null)
{
using (myStream)
{
String tifFileName= openTifDialog.FileName;
imgLocation = tifFileName;
Bitmap tifFile = new Bitmap(tifFileName);
return tifFile;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
return null;
}
这是我保存图像的方式:
private void saveImage(Image img)
{
SaveFileDialog sf = new SaveFileDialog();
sf.Title = "Select File Location";
sf.Filter = " bmp (*.bmp)|*.bmp|jpeg (*.jpg)|*.jpg|tiff (*.tif)|*.tif";
sf.FilterIndex = 4;
sf.RestoreDirectory = true;
sf.ShowDialog();
// If the file name is not an empty string open it for saving.
if (sf.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)sf.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
switch (sf.FilterIndex)
{
case 1:
img.Save(fs,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 2:
img.Save(fs,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 3://EDITED -STILL DOES NOT RESOLVE THE ISSUE
ImageCodecInfo codecInfo = ImageClass.GetEncoderInfo(ImageFormat.Tiff);
EncoderParameters parameters = new EncoderParameters(2);
parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,100L);
parameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionNone);
img.Save(fs,codecInfo, parameters);
break;
}
fs.Close();
}
}
即使我不以任何方式调整图像大小或更改图像,我的质量也会有所下降。有什么建议吗?
【问题讨论】:
-
更新:查看保存图像的 irfanview 上的信息并将其与原始图像进行比较,我注意到两件事:一是原始图像中的压缩显示没有,在保存的图像中LZW 说。我注意到的另一件事是,虽然两个图像中的颜色保持为每像素 8 位(256 种颜色),但保存图像中的唯一颜色计数为 16,而原始图像中的唯一颜色计数为 251
-
更新:我更改了代码以将其保存为 100% 质量并消除压缩,但保存图像中唯一颜色的 # 仍为 16,我仍然可以看到差异两个图像的质量。也许问题出在打开图像时的构造函数中?