如何使用GDI +使用Alpha通道调整PNG图像的大小?

zig*_*zig 5 delphi png gdi+ resize delphi-7

在寻找一种方法来调整TPngObject的大小并保持透明度+ alpha通道无济于事之后,我正在尝试使用GDI +

这是我的代码,它似乎工作正常.它将向下/向上缩放PNG.到目前为止在XP上测试过:

uses GDIPAPI, GDIPOBJ, GDIPUTIL; 

procedure TForm1.Button1Click(Sender: TObject);
var
  encoderClsid: TGUID;
  stat: TStatus;
  img, img_out: TGPImage;
begin
  img := TGPImage.Create('in.png'); // 200 x 200  
  img_out := img.GetThumbnailImage(100, 100, nil, nil);
  GetEncoderClsid('image/png', encoderClsid);
  img_out.Save('out.png', encoderClsid);
  img_out.free;
  img.Free;
end;
Run Code Online (Sandbox Code Playgroud)

我的问题:正在使用GetThumbnailImage正确的方法吗?我没有找到任何其他方法.

TLa*_*ama 7

我不认为这种GetThumbnailImage方法是一种很好的方法,因为我怀疑你会获得高质量的重采样图像.在本文中,您可以找到如何重新缩放图像.他们正在使用这种DrawImage方法,所以我也会这样做.就在此之前,我还将设置高质量的图形模式以获得高质量的输出.这是一个例子:

procedure TForm1.Button1Click(Sender: TObject);
var
  Input: TGPImage;
  Output: TGPBitmap;
  Encoder: TGUID;
  Graphics: TGPGraphics;
begin
  Input := TGPImage.Create('C:\InputImage.png');
  try
    // create the output bitmap in desired size
    Output := TGPBitmap.Create(100, 100, PixelFormat32bppARGB);
    try
      // create graphics object for output image
      Graphics := TGPGraphics.Create(Output);
      try
        // set the composition mode to copy
        Graphics.SetCompositingMode(CompositingModeSourceCopy);
        // set high quality rendering modes
        Graphics.SetInterpolationMode(InterpolationModeHighQualityBicubic);
        Graphics.SetPixelOffsetMode(PixelOffsetModeHighQuality);
        Graphics.SetSmoothingMode(SmoothingModeHighQuality);
        // draw the input image on the output in modified size
        Graphics.DrawImage(Input, 0, 0, Output.GetWidth, Output.GetHeight);
      finally
        Graphics.Free;
      end;
      // get encoder and encode the output image
      if GetEncoderClsid('image/png', Encoder) <> -1 then
        Output.Save('C:\OutputImage.png', Encoder)
      else
        raise Exception.Create('Failed to get encoder.');
    finally
      Output.Free;
    end;
  finally
    Input.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

  • 别客气!由于输出位图格式(我必须明确指定,即使由于模糊的过载而导致默认值),也会保留alpha通道.如果您使用例如'PixelFormat32bppRGB`,您将失去alpha通道.渲染本身也考虑透明度(即使在纯GDI中). (3认同)
  • 是的,你可以省略它们.但是你可能会得到与缩略图相同的结果(这只是一个猜测,但我相信它们在内部做的与上面的代码类似,只是没有提高质量).这里使用的设置是为了获得最高质量的输出,这需要额外的计算时间.你可以尝试修改它们甚至低于默认质量,但最终你可能会得到难看的结果.默认模式是`InterpolationModeDefault =?`,'PixelOffsetModeDefault = PixelOffsetModeNone`和`SmoothingModeDefault = no smoothing`(源MSDN). (2认同)