Search code examples
delphidelphi-7

Create an image and colored ir?


how can I create an image and how can I colored it pixel by pixel using hexadecimal code of colors?

For ex. I wanna create a 100x100 pixel image and I wanto to 1x1 area's color is '$002125',2x2 area's color is '$125487'.... How can I do it?

Thank you for your answers..


Solution

  • Made a simple sample for you. Using Canvas.Pixels not Scanline. Scanline is faster though but for start I think it suits just fine. The colors are randomly generated, so you just need to replace this part of the code.

        procedure TForm1.GenerateImageWithRandomColors;
        var
          Bitmap: TBitmap;
          I, J: Integer;
          ColorHEX: string;
    
        begin
          Bitmap := TBitmap.Create;
          Randomize;
    
          try
            Bitmap.PixelFormat := pf24bit;
            Bitmap.Width := 100;
            Bitmap.Height := 100;
    
            for I := 0 to Pred(Bitmap.Width) do
            begin
              for J := 0 to Pred(Bitmap.Height) do
              begin
                Bitmap.Canvas.Pixels[I, J] := RGB(Random(256),
                   Random(256),
                   Random(256));
    
                // get the HEX value of color and do something with it
                ColorHEX := ColorToHex(Bitmap.Canvas.Pixels[I, J]);
              end;
            end;
    
            Bitmap.SaveToFile('test.bmp');
          finally
            Bitmap.Free;
          end;
        end;
    
    function TForm1.ColorToHex(Color : TColor): string;
    begin
      Result :=
         IntToHex(GetRValue(Color), 2) +
         IntToHex(GetGValue(Color), 2) +
         IntToHex(GetBValue(Color), 2);
    end;