2011-07-06 51 views
2

我想从字符串保存图像。如何以英寸为单位设置图像高度和宽度?

所以我想知道如何在保存图像时以英寸为单位设置图像的高度和宽度。

我的代码如下图像保存:

private void Base64ToImage(string base64String) 
    { 
     Image fullSizeImg = null; 
     byte[] imageBytes = Convert.FromBase64String(base64String); 
     MemoryStream ms = new MemoryStream(imageBytes); 
     fullSizeImg = Image.FromStream(ms, true); 
     System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); 
     System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(700, 800, dummyCallBack, IntPtr.Zero); 
     thumbNailImg.Save(ImagePath, System.Drawing.Imaging.ImageFormat.Png); 
     fullSizeImg.Dispose(); 
     thumbNailImg.Dispose(); 


    } 
+0

你为什么要这么做? –

+0

@Tarun,这是一个奇特而消极的评论。我可以想出十几个创建基于base64编码的图像的原因,并且希望能够在物理尺寸上显示/打印图像而不是按比例显示图像 - 这是一个非常常见的问题,WPF在很大程度上决定解决这个问题。 – Smudge202

+0

@Smudge对不起,如果我听起来负面/粗鲁,只是想知道,为什么他/她想以英寸而不是像素保存图像! –

回答

3

位图不具有以英寸为单位的尺寸,其尺寸以像素为单位进行测量。这就是说最现代化的bitmat格式有一块被称为DPI(每英寸点数)的元数据,用来在像素尺寸以英寸为单位通过简单的公式转换为一个大小:

inches = pixels/dpi 

对于所设置的图像类使用其中的元数据的碎片,我们感兴趣的SetPropertyItem Method元数据是:

  • PropertyTagResolutionUnit - 基本上,X DPI只要PropertyTagResolutionUnit单位为英寸 - 这对于英寸
  • PropertyTagXResolution设置为“2”。
  • PropertyTagYResolution - 在Y DPI只要PropertyTagResolutionUnit是英寸

Property Item Descriptions了解详情。

(其实,我通过写这个,使用SetPropertyItem属性元数据的设置看起来很复杂实现了一半 - 你可能只是最好使用Bitmat相反,它具有分辨率特性使整个事情容易得多)

8

这是行不通的。我们节省了像素,因为英寸/厘米/英里不会转换为屏幕上的房地产。原因是我们都使用不同的DPI设置,尽管92 DPI似乎是当今更常见的设置之一。

还有一些不同的打印机DPI设置...

要计算从英寸像素,你可以尝试:

pixels = inches * someDpiSetting 

但是记住,这将不会导致每个屏幕上英寸,每一个打印输出等等。

编辑:如果你看看WPF,你会发现它对DPI有着出色的支持,并且不管DPI如何将表单转换为相同的(给定或取出)大小。也许这有帮助?

2

如果你使用的是位图,那么它有方法SetResoution(http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.setresolution.aspx),它允许你设置x并且可以很容易地从您对图像高度和宽度的知识中获得dpi和dpi,这些图像以像素和英寸表示。

我希望在这里使用位图而不是图像应该不成问题。它的一个子类,所以我想可能你可以。

1

作为对比,这些帝国的措施和配方只能是:

// inches = pixels/dpi 
    // pixel = inches * dpi 
    // 1 centimeter = 0.393700787 inch 
    // pixel = cm * 0.393700787 * dpi 


    single sngWidth = 2.25; //cm 
    single sngHeight = 1.0; //cm 
    sngWidth *= 0.393700787 * bmpImage.HorizontalResolution; // x-Axis pixel 
    sngHeight *= 0.393700787 * bmpImage.VerticalResolution; // y-Axis pixel 

像这样:

public static int Cm2Pixel(double WidthInCm) 
{ 
    double HeightInCm = WidthInCm; 
    return Cm2Pixel(WidthInCm, HeightInCm).Width; 
} // End Function Cm2Pixel 


public static System.Drawing.Size Cm2Pixel(double WidthInCm, double HeightInCm) 
{ 
    float sngWidth = (float)WidthInCm; //cm 
    float sngHeight = (float)HeightInCm; //cm 
    using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1)) 
    { 
     sngWidth *= 0.393700787f * bmp.HorizontalResolution; // x-Axis pixel 
     sngHeight *= 0.393700787f * bmp.VerticalResolution; // y-Axis pixel 
    } 

    return new System.Drawing.Size((int)sngWidth, (int)sngHeight); 
} // End Function Cm2Pixel 
相关问题