Pages

Friday 31 May 2024

Calculating CRC32 File Hash in Delphi

In software development, ensuring data integrity and verifying whether a file has changed is a common requirement. One effective way to achieve this is by using the CRC32 (Cyclic Redundancy Check) hash, which is a popular method for detecting changes in files. In this blog post, we will explore a Delphi function that calculates the CRC32 hash of a file, allowing you to detect any modifications easily.

Let's dive into the function:

function PACalculateCRC32FromFile(const FileName: string): string;

// Calculate FAST CRC32 File Hash (e.g. for the purpose of detecting if a file has changed)

var

  IdCRC32: IdHashCRC.TIdHashCRC32;        // Declare a variable to hold the CRC32 hash object

  FileStream: System.Classes.TFileStream; // Declare a variable to hold the file stream

  CRC32: Cardinal;                        // Declare a variable to hold the CRC32 value

begin

  IdCRC32 := TIdHashCRC32.Create;   // Create an instance of the CRC32 hash object

  try

    // The file specified by FileName is opened in read-only mode with shared deny-write access.

    // This ensures that the file can be read while preventing other processes from writing to it:

    FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); // Open the file for reading

    try

      CRC32 := IdCRC32.HashValue(FileStream); // Calculate the CRC32 value of the file

      // The computed CRC32 value, which is a Cardinal type, is converted to an 8-character hexadecimal string.

      // This makes the result more readable and suitable for comparison purposes:

      Result := IntToHex(CRC32, 8);           // Convert the CRC32 value to a hexadecimal string

    finally

      FileStream.Free;  // Ensure the file stream is freed even if an exception occurs

    end;

  finally

    IdCRC32.Free;  // Ensure the CRC32 hash object is freed even if an exception occurs

  end;

end;

Tuesday 21 May 2024

HOW TO SAVE AN IMAGE AS AN HTML WEB PAGE WITH OPTIONAL HYPERLINK

ImageEn is one of the best and most popular image libraries for Embarcadero Delphi.

Here is a single function to save an image from TImageEnView as an HTML web page with an optional hyperlink and automatically open it ready to use in your default web browser:

The function first asks for the filename of the HTML Web Page. Then, it prompts the user for an optional Hyperlink URL. Then, it automatically opens the saved HTML Web Page in the user's default web browser. If a HyperLink URL was provided, clicking the image automatically navigates to the provided URL.

Here is a Delphi demo project that contains the demo source and a compiled (signed) executable:

SaveImageAsHTML_Demo.zip

uses

  Vcl.Imaging.jpeg, Vcl.Imaging.pngimage, Vcl.Graphics, System.Classes, System.SysUtils,

  IdCoderMIME, ImageEnView, Vcl.Dialogs, ShellAPI, Vcl.Forms;


procedure SaveImageAsHTML(ImageEnView: TImageEnView);

var

  MemoryStream: TMemoryStream;

  Base64Stream: TStringStream;

  Base64Encoder: TIdEncoderMIME;

  HTMLFile: TStringList;

  Base64Image: string;

  SaveDialog: TSaveDialog;

  JPEGImage: TJPEGImage;

  HTMLFileName: string;

  ImageLink: string;

  LinkProvided: Boolean;

begin

  SaveDialog := TSaveDialog.Create(nil);

  SaveDialog.DefaultExt := 'html';

  SaveDialog.Filter := 'HTML files (*.html)|*.html';

  SaveDialog.Options := [ofOverwritePrompt, ofPathMustExist];


  try

    if not SaveDialog.Execute then

      Exit; // User cancelled the save dialog


    // Prompt the user to OPTIONALLY enter an image hyperlink:

    LinkProvided := InputQuery('OPTIONALLY enter an image hyperlink URL', 'URL:', ImageLink);

    // if the user enters no URL (or hits the ESC key) then the image web page is saved normally with no hyperlink


    HTMLFileName := SaveDialog.FileName;


    MemoryStream := TMemoryStream.Create;

    Base64Stream := TStringStream.Create;

    Base64Encoder := TIdEncoderMIME.Create(nil);

    HTMLFile := TStringList.Create;

    JPEGImage := TJPEGImage.Create;


    try

      // Convert the TImageEnView image to JPEG with 100% quality

      JPEGImage.Assign(ImageEnView.Bitmap);

      JPEGImage.CompressionQuality := 100;

      JPEGImage.SaveToStream(MemoryStream);

      MemoryStream.Position := 0;


      // Encode the image to Base64

      Base64Encoder.Encode(MemoryStream, Base64Stream);

      Base64Image := Base64Stream.DataString;


      // Create the HTML content

      HTMLFile.Add('<html>');

      HTMLFile.Add('<head>');

      HTMLFile.Add('<style>');

      HTMLFile.Add('  body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }');

      HTMLFile.Add('  .container { text-align: center; }');

      HTMLFile.Add('</style>');

      HTMLFile.Add('</head>');

      HTMLFile.Add('<body>');

      HTMLFile.Add('<div class="container">');


      if LinkProvided and (ImageLink <> '') then

        HTMLFile.Add('<a href="' + ImageLink + '">');


      HTMLFile.Add('<img src="data:image/jpeg;base64,' + Base64Image + '">');


      if LinkProvided and (ImageLink <> '') then

        HTMLFile.Add('</a>');


      HTMLFile.Add('</div>');

      HTMLFile.Add('</body>');

      HTMLFile.Add('</html>');


      // Save the HTML content to a file

      HTMLFile.SaveToFile(HTMLFileName);


      // Open the saved HTML file in the default browser

      ShellExecute(0, 'open', PChar(HTMLFileName), nil, nil, SW_SHOWNORMAL);

    finally

      MemoryStream.Free;

      Base64Stream.Free;

      Base64Encoder.Free;

      HTMLFile.Free;

      JPEGImage.Free;

    end;

  finally

    SaveDialog.Free;

  end;

end;



Monday 6 May 2024

HOW TO GET THE MOST FREQUENT COLORS IN AN IMAGE BY USING EMBARCADERO DELPHI

ImageEn is one of the best and most popular image libraries for Embarcadero Delphi.

Here, I use it in my new Screenshot Software Application:


I needed a function to extract the 16 most frequent colors from the above screenshot image:

This function returns the most frequent colors in TImageEnView in order of frequency























After having retrieved the 16 most frequent colors from the Notepad screenshot image above, I assign them to the CUSTOM COLORS of a Color Dialog:


I use this Color Dialog in my screenshot application to select a color for a FloodFill feature to edit the screenshot image.

Here, I added a colorful illustration to the screenshot image:


Please note how the Custom Colors have changed after having applied the above function to the illustrated screenshot image:

Sierpinski Triangle Fractal version 2.0

 This is a substantial update from yesterday's article Creating a Fractal Art Application: Drawing the Sierpinski Triangle . What's ...