Resize image in NAV 2018

For a period there was an issue with printing images in reports. They all look kind of distorted / scrambled. After a while I figured out that the reason for this was the image size stored in the blob field. So what to do? Well, I made a new function, which could resize the image automatically.

The following function (procedure) ResizeImages can import a image file, resize the image and then save the file again.
All this is now possible in NAV 2018 thanks to the use of .NET.

PROCEDURE ResizeImage(FileName : Text;UpsizeIfSmaller : Boolean;MaintainAspectRatio : Boolean;NewWidth : Integer;NewHeight : Integer);
VAR
   TempBlob : TEMPORARY Record 90000;
   ItemDesignSetup : Record 90000;
   Bitmap : System.Drawing.Bitmap;
   ImageFormat : System.Drawing.Imaging.ImageFormat;
   InStr : InStream;
   OutStr : OutStream;
   AspectRatio : Decimal;
BEGIN

   ItemDesignSetup.GET;

   IF (NewWidth = 0) OR (NewHeight = 0) THEN BEGIN
      NewWidth := ItemDesignSetup."Resize Width";
      NewHeight := ItemDesignSetup."Resize Height";
   END;

   IF (NewWidth = 0) OR (NewHeight = 0) THEN
      EXIT;

   TempBlob.INIT;

   //Load image
   TempBlob."Temp Resized Picture".IMPORT(FileName);
   TempBlob."Temp Resized Picture".CREATEINSTREAM(InStr);

   Bitmap := Bitmap.Bitmap(InStr);

   //Calculate new size
   IF NOT UpsizeIfSmaller THEN
      IF (NewWidth >= Bitmap.Width) OR (NewHeight >= Bitmap.Height) THEN
         EXIT;

   IF Bitmap.Width / NewWidth < Bitmap.Height / NewHeight THEN
      AspectRatio := Bitmap.Width / NewWidth
   ELSE
      AspectRatio := Bitmap.Height / NewHeight;

   IF MaintainAspectRatio THEN BEGIN
      NewHeight := ROUND(Bitmap.Height / AspectRatio, 1, '<');
      NewWidth := ROUND(Bitmap.Width / AspectRatio, 1, '<');
   END;

   //Resize image
   CLEAR(TempBlob."Temp Resized Picture");
   TempBlob."Temp Resized Picture".CREATEOUTSTREAM(OutStr);
   Bitmap := Bitmap.Bitmap(Bitmap,NewWidth,NewHeight);

   //Save resized image
   Bitmap.Save(OutStr,ImageFormat.Jpeg);
   Bitmap.Save(FileName, ImageFormat.Jpeg);
END;

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.