c#设置图片的dpi_在C#中将DPI值设置为Tiff图像

I'm trying to set dpi value of a TIFF Image in C# through code but somehow the values are not persisted after saving the Image.

using (var image = new Bitmap(@"c:\newimage.tif"))

{

uint[] uintArray = { 300, 1}; //Setting DPI as 300

byte[] bothArray = ConvertUintArrayToByteArray(uintArray);

PropertyItem item = image.PropertyItems.Where(p => p.Id == 0x11A).Single();

var val = BitConverter.ToUInt32(item.Value, 0);

Console.WriteLine(val);

item.Id = 0x11A;

item.Value = bothArray;

item.Type = 5;

item.Len = item.Value.Length;

image.SetPropertyItem(item);

image.Save(@"c:\newimage1.tif"); //Save image to new File

}

What is wrong with this code? Any kind of help would be appreciated.

TIFF file tag definitions

解决方案

Setting both the property value and the bitmap resolution and then resaving the image should change the resolution (It worked on my sample image). I believe the original file has to have the tags for X and Y resolution present, not sure if .NET will add those tags if not present (would have to test).

Here's an example of reading and writing the X and Y resolution a TIFF image using .NET:

int numerator, denominator;

using (Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\input.tif"))

{

// obtain the XResolution and YResolution TIFFTAG values

PropertyItem piXRes = bmp.GetPropertyItem(282);

PropertyItem piYRes = bmp.GetPropertyItem(283);

// values are stored as a rational number - numerator/denominator pair

numerator = BitConverter.ToInt32(piXRes.Value, 0);

denominator = BitConverter.ToInt32(piXRes.Value, 4);

float xRes = numerator / denominator;

numerator = BitConverter.ToInt32(piYRes.Value, 0);

denominator = BitConverter.ToInt32(piYRes.Value, 4);

float yRes = numerator / denominator;

// now set the values

byte[] numeratorBytes = new byte[4];

byte[] denominatorBytes = new byte[4];

numeratorBytes = BitConverter.GetBytes(600); // specify resolution in numerator

denominatorBytes = BitConverter.GetBytes(1);

Array.Copy(numeratorBytes, 0, piXRes.Value, 0, 4); // set the XResolution value

Array.Copy(denominatorBytes, 0, piXRes.Value, 4, 4);

Array.Copy(numeratorBytes, 0, piYRes.Value, 0, 4); // set the YResolution value

Array.Copy(denominatorBytes, 0, piYRes.Value, 4, 4);

bmp.SetPropertyItem(piXRes); // finally set the image property resolution

bmp.SetPropertyItem(piYRes);

bmp.SetResolution(600, 600); // now set the bitmap resolution

bmp.Save(@"C:\output.tif"); // save the image

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值