gpt4 book ai didi

c# - 在保留元数据的同时调整大小和保存图像

转载 作者:太空狗 更新时间:2023-10-29 20:37:51 25 4
gpt4 key购买 nike

我正在尝试调整图像大小并保存图像,这相当简单(例如, 查看此示例 external example no longer valid)。

但是,使用此代码会从图像中剥离元数据信息。我似乎不太明白如何保留 jpeg 图像的元数据。

编辑:示例代码

public static void ResizeMethodThree(string sourceFile, string targetFile)
{
byte[] baSource = File.ReadAllBytes(sourceFile);

PropertyItem[] propertyItems = new Bitmap(sourceFile).PropertyItems;

using (Stream streamPhoto = new MemoryStream(baSource))
{
BitmapFrame bfPhoto = ReadBitmapFrame(streamPhoto);
BitmapMetadata metaData = (BitmapMetadata)bfPhoto.Metadata;
int nNewPictureSize = 200;
int nWidth = 0;
int nHeight = 0;

if (bfPhoto.Width > bfPhoto.Height)
{
nWidth = nNewPictureSize;
nHeight = (int)(bfPhoto.Height * nNewPictureSize / bfPhoto.Width);
}
else
{
nHeight = nNewPictureSize;
nWidth = (int)(bfPhoto.Width * nNewPictureSize / bfPhoto.Height);
}

BitmapFrame bfResize = ResizeHelper(bfPhoto, nWidth, nHeight, BitmapScalingMode.HighQuality);

byte[] baResize = ToByteArray(bfResize);

File.WriteAllBytes(targetFile, baResize);

Image targetImage = new Bitmap(targetFile);
foreach (var propertyItem in propertyItems)
{
targetImage.SetPropertyItem(propertyItem);
}

targetImage.Save(targetFile);
}
}

public static BitmapFrame ResizeHelper(BitmapFrame photo, int width,
int height, BitmapScalingMode scalingMode)
{

var group = new DrawingGroup();
RenderOptions.SetBitmapScalingMode(
group, scalingMode);
group.Children.Add(
new ImageDrawing(photo,
new Rect(0, 0, width, height)));
var targetVisual = new DrawingVisual();
var targetContext = targetVisual.RenderOpen();
targetContext.DrawDrawing(group);
var target = new RenderTargetBitmap(
width, height, 96, 96, PixelFormats.Default);
targetContext.Close();
target.Render(targetVisual);
var targetFrame = BitmapFrame.Create(target);
return targetFrame;
}

private static byte[] ToByteArray(BitmapFrame bfResize)
{
using (MemoryStream msStream = new MemoryStream())
{
JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
jpgEncoder.Frames.Add(bfResize);
jpgEncoder.Save(msStream);
return msStream.ToArray();
}
}

private static BitmapFrame ReadBitmapFrame(Stream streamPhoto)
{
BitmapDecoder bdDecoder =
BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
return bdDecoder.Frames[0];
}

最佳答案

使用源图像上的 Image.PropertyItems 属性获取元数据项列表。遍历列表,对目标图像调用 Image.SetPropertyItem。您通常应该避免调整大小和重新压缩 jpeg 图像,使用未压缩的原始图像最好保持质量并避免伪影。

关于c# - 在保留元数据的同时调整大小和保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com