gpt4 book ai didi

delphi - 如何在 Delphi 中使用 WIC 创建无损 jpg

转载 作者:行者123 更新时间:2023-12-03 14:44:24 30 4
gpt4 key购买 nike

我有以下代码可以使用默认选项从 IWICBitmapSource 创建一个 jpg 文件:

function SaveWICBitmapToJpgFile(WICFactory: IWICImagingFactory;
WICBitmap: IWICBitmapSource; SrcRect: TRect; FileName: string): HRESULT;
var
hr: HRESULT;
Encoder: IWICBitmapEncoder;
Frame: IWICBitmapFrameEncode;
PropBag: IPropertyBag2;
S: IWICStream;
PixelFormatGUID: WICPixelFormatGUID;
R: WICRect;
begin

hr := WICFactory.CreateStream(S);

if Succeeded(hr) then begin
hr := S.InitializeFromFilename(PChar(FileName), GENERIC_WRITE);
end;

if Succeeded(hr) then begin
hr := WICFactory.CreateEncoder(GUID_ContainerFormatJpeg, GUID_NULL,
Encoder);
end;

if Succeeded(hr) then begin
hr := Encoder.Initialize(S, WICBitmapEncoderNoCache);
end;

if Succeeded(hr) then begin
hr := Encoder.CreateNewFrame(Frame, PropBag);
end;

if Succeeded(hr) then begin
hr := Frame.Initialize(PropBag);
end;

if Succeeded(hr) then begin
hr := Frame.SetSize(SrcRect.Width, SrcRect.Height);
end;

if Succeeded(hr) then begin
PixelFormatGUID := GUID_WICPixelFormat24bppBGR;
hr := Frame.SetPixelFormat(PixelFormatGUID);
end;

if Succeeded(hr) then begin
hr := IfThen(PixelFormatGUID = GUID_WICPixelFormat24bppBGR, S_OK, E_FAIL);
end;

if Succeeded(hr) then begin
R.X := SrcRect.Left;
R.Y := SrcRect.Top;
R.Width := SrcRect.Width;
R.Height := SrcRect.Height;
Frame.WriteSource(WICBitmap, @R);
end;

if Succeeded(hr) then begin
hr := Frame.Commit;
end;

if Succeeded(hr) then begin
hr := Encoder.Commit;
end;

Result := hr;

end;

我想更改编解码器选项以生成无损 jpg。根据我在 MSDN 中读到的内容,我必须使用 IPropertyBag2 来实现这一点。尽管不知道如何做,我还是尝试在 Frame 创建和 Frame 初始化之间插入此代码:
var
[...]
PropBagOptions: TPropBag2;
V: Variant;
[...]

if Succeeded(hr) then begin
FillChar(PropBagOptions, SizeOf(PropBagOptions), 0);
PropBagOptions.pstrName := 'ImageQuality';
V := 1.0;
hr := PropBag.Write(1, @PropBagOptions, @V);
end;

它不起作用:hr = 0x88982F8E(WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE)。 MSDN 说 here “ImageQuality”属性的类型是 VT_R4,但由于我以前从未使用过 Variant,我不确定如何编写它。而且我什至不确定压缩是否确实是无损的。

我怎样才能修改我的代码以使其产生高质量的 1.0 jpg,并且它是无损的?

最佳答案

我没有这方面的经验,但这是我根据阅读您链接到的文档得出的最佳建议。

首先,我认为您需要指定更多 PropBagOptions 的成员:

  • dwType需要设置为 PROPBAG2_TYPE_DATA .
  • vt需要设置为 VT_R4 .

  • 您还需要确保该变体确实是 VT_R4 .这是一个 4 字节的实数,用 Delphi 术语来说是 varSingle 类型的变体.
    V := VarAsType(1.0, varSingle);

    我认为这应该可以完成。

    把它们放在一起,它看起来像这样:
    FillChar(PropBagOptions, SizeOf(PropBagOptions), 0);
    PropBagOptions.pstrName := 'ImageQuality';
    PropBagOptions.dwType := PROPBAG2_TYPE_DATA;
    PropBagOptions.vt := VT_R4;
    V := VarAsType(1.0, varSingle);
    hr := PropBag.Write(1, @PropBagOptions, @V);

    至于JPEG质量1.0是否无损,则不是。这是一个在这里已经很好地涵盖的问题: Is JPEG lossless when quality is set to 100?

    关于delphi - 如何在 Delphi 中使用 WIC 创建无损 jpg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14584838/

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