unit BMP_JPEGformat;

interface

uses IOGraphics, Jpeg;

procedure GetBmpJpegInfo(FileName : string; var Info: TImgRec; DisplayWarnings : boolean);
procedure LoadBmpJpegImage(var Info : TImgRec; var  Img : Pointer);

implementation

uses Graphics, SysUtils, Dialogs;

procedure GetBmpJpegInfo(FileName : string; var Info: TImgRec; DisplayWarnings : boolean);
var ext      : string;
    JpgImage : TJPEGImage;
begin
  Info.OK:=true;
  Info.Error:='';
  Info.Bitmap:=Graphics.TBitmap.Create;
  if not FileExists(FileName) then
    begin
     Info.OK:=false;
     Info.Error:='File not found.';
     Exit;
    end;
  ext:=UpperCase(ExtractFileExt(FileName));
  if ext='.BMP' then Info.Bitmap.LoadFromFile(FileName);
  if ext='.JPG' then
    begin
      JpgImage:=TJPEGImage.Create;
      JpgImage.LoadFromFile(FileName);
      Info.Bitmap.Assign(JpgImage);
      JpgImage.Destroy;
    end;
  Info.FileName:=FileName;
  Info.ImgWidth:=Info.Bitmap.Width;
  Info.ImgHeight:=Info.Bitmap.Height;
  Info.DataType:='BYTE';
  Info.HeaderSize:=-1;
  Info.RGBsepatated:=false;
  case Info.Bitmap.PixelFormat of
    pf8bit  : Info.Channels:=1;
    pf24bit : Info.Channels:=3;
    pf32bit : Info.Channels:=3; // bude konvertovano na pf24bit;
  else
    Info.OK:=false;
    Info.Error:='File '+ExtractFileName(FileName)+' has unsupported BMP pixel format.';
    if DisplayWarnings then ShowMessage(Info.Error);
  end{case};
  Info.BytesPerPixel:=Info.Channels;
  Info.ImgSize:=Info.ImgWidth*Info.ImgHeight*Info.BytesPerPixel;
  Info.SwapBytes:=false;
  Info.VertFlip:=false;
  Info.BZero:=0;
  Info.BScale:=1;
  Info.DataMin:=1;
  Info.DataMax:=-1;
end;

procedure LoadBmpJpegImage(var Info : TImgRec; var  Img : Pointer);
type TBArry = array[0..10000*10000] of byte;
     PBArry = ^TBArry;
var Lin, ImgB : PBArry;
    i, j      : integer;
    r, g, b   : byte;
    P         : pointer;
begin
  Info.OK:=false;
  if Info.Bitmap=nil then Exit;
  ImgB:=Img;
  Info.OK:=true;
  for j:=0 to Info.ImgHeight - 1 do
    begin
      Lin:=Info.Bitmap.ScanLine[j];
      {vymena R,B}  
      if Info.Bitmap.PixelFormat=pf24bit then for i:=0 to Info.ImgWidth-1 do
        begin
          b:=Lin[3*i];
          Lin[3*i]:=Lin[3*i+2];
          Lin[3*i+2]:=b;
        end;
      {konverze 32 bit na 24 bit a vymena R,B}
      if Info.Bitmap.PixelFormat=pf32bit then for i:=0 to Info.ImgWidth-1 do
        begin
          r:=Lin[4*i+2];
          g:=Lin[4*i+1];
          b:=Lin[4*i  ];
          Lin[3*i  ]:=r;
          Lin[3*i+1]:=g;
          Lin[3*i+2]:=b;
        end;
      P:=addr(ImgB^[j*Info.ImgWidth*Info.BytesPerPixel]);
      Move(Lin^,P^,Info.ImgWidth*Info.BytesPerPixel);
    end;
  Info.Bitmap.Destroy;
  Info.Bitmap:=nil;
end;

end.
