unit Webp2Jpeg;

interface

uses
  Classes, Graphics, libwebp, Jpeg;

function WebPToJpeg(AWebPStream: TStream): TJpegImage;


implementation

function WebPToJpeg(AWebPStream: TStream): TJpegImage;
var
  Buffer: array of Byte;
  Bitmap: TBitmap;
  Width, Height: Integer;
  Decoded: PAnsiChar;
  SourceRow, DestRow: PAnsiChar;
  RowSize: NativeUInt;
  Y: Integer;
begin
  Result := nil;
  if (AWebPStream = nil) then
    exit;
  SetLength(Buffer, AWebPStream.Size - AWebPStream.Position);
  if Length(Buffer) = 0 then
    exit;

  AWebPStream.ReadBuffer(Buffer[0], Length(Buffer));


  if WebPGetInfo(@Buffer[0], Length(Buffer), @Width, @Height) = 0 then
    exit;

  RowSize := NativeUInt(Width) * 4;

  GetMem(Decoded, RowSize * NativeUInt(Height));
  try
    if WebPDecodeBGRAInto(
      @Buffer[0],
      Length(Buffer),
      PByte(Decoded),
      RowSize * NativeUInt(Height),
      Integer(RowSize)) = nil then
        exit;

    Bitmap := TBitmap.Create;
    try
      Bitmap.PixelFormat := pf32bit;
      Bitmap.Width := Width;
      Bitmap.Height := Height;

      for Y := 0 to Height - 1 do
      begin
        SourceRow := Decoded + NativeUInt(Y) * RowSize;
        DestRow := Bitmap.ScanLine[Y];
        Move(SourceRow^, DestRow^, RowSize);
      end;

      Result := TJPEGImage.Create;
      Result.Assign(Bitmap);
    finally
      Bitmap.Free;
    end;
  finally
    FreeMem(Decoded);
  end;
end;

end.
