Solved

Looking for a way to rotate an image...

Posted on 1998-06-08
23
398 Views
Last Modified: 2010-04-03
Hi!

How can I do the following: Load an TImage from disk (BMP) or from an TJPEGImage, rotate the image 90, 180 or 270 degrees and then save the image to disk again? I can figure out the loading and saving just fine, but how do I rotate the picture? The picture will be about 800x600 pixels big.

Thanks!

//Daniel, Sweden
0
Comment
Question by:Dippen
  • 8
  • 6
  • 5
  • +4
23 Comments
 

Author Comment

by:Dippen
ID: 1351566
Edited text of question
0
 

Expert Comment

by:heapster
ID: 1351567
This questions has been answered previously - look through the archives.
0
 

Expert Comment

by:heapster
ID: 1351568
But in case this was all you wanted to know:

POINTS CAN BE ROTATED THROUGH AN ANGLE theta ABOUT THE ORIGIN. A ROTATION IS DEFINED MATHEMATICALLY BY

x' = x * costheta - y * sintheta,
y' = x * sintheta + y * costheta.

0
 

Expert Comment

by:heapster
ID: 1351569
Question 306 dealt with this.
0
 
LVL 2

Expert Comment

by:odessa
ID: 1351570
This is not a so easy but something like this,
You will need 2 TImage objects (may be one temporary) one original, and one new,
with Canvas.Pixels, properiti of TImage you can read&write pixels with TColor, now the only thing you need to do is to preform procedure that gets a pixels from original and put them into new image, thas oll folcs
0
 

Expert Comment

by:heapster
ID: 1351571
Question 306 dealt with this.
0
 

Expert Comment

by:heapster
ID: 1351572
I DONT UNDERSTAND HOW ODESSAS PROPOSED ANSWER ANSWERS THE QUESTION - HE COMPLETELY MISSED THE POINT WHICH WAS HOW TO ROTATE THE IMAGE.  WHATS GOING ON?
0
 

Expert Comment

by:heapster
ID: 1351573
I POSTED THIS EARLIER, BUT IT DIDNT GET THROUGH.

POINTS CAN BE ROTATED THROUGH AN ANGLE theta ABOUT THE ORIGIN. A ROTATION IS DEFINED MATHEMATICALLY BY

x' = x * costheta - y * sintheta,
y' = x * sintheta + y * costheta.
0
 

Expert Comment

by:heapster
ID: 1351574
I POSTED THIS EARLIER, BUT IT DIDNT GET THROUGH.

POINTS CAN BE ROTATED THROUGH AN ANGLE theta ABOUT THE ORIGIN. A ROTATION IS DEFINED MATHEMATICALLY BY

x' = x * costheta - y * sintheta,
y' = x * sintheta + y * costheta.
0
 

Expert Comment

by:heapster
ID: 1351575
errr.. sorry about all that chaps.  I've had a stressful few days.
0
 
LVL 4

Expert Comment

by:d003303
ID: 1351576
heapster,
if you only have 90, 180 or 270 degrees rotation, you will not need sin or cos, because for those angles their value is an integer. To speed the rotation procedure it up, you just pre-code the transform values (e.g. for 90 degrees, x' would be x * 0 - y * -1).
About your comments, everybody is free to answer a question, even if the answer is totaly wrong or missed the point. Dippen has to decide this by accepting or rejecting it.
You do not need to re-post the same comment several times. Unlike internet newsgroups, it is ensured that once you posted a comment it stays posted. And please, stop shouting around.

Dippen,
Here's some code that is quite fast. Create a form, drop a button and 2 images on it. Load a bitmap into the first image and set the second image to AutoSize=true. Also, add this to your form declaration :

  private
    { Private declarations }
    RotImage : TBitmap;
    RotAngle : Integer;
  end;

Create handlers for the forms OnCreate and the buttons OnClick event and use this code:

procedure TForm1.FormCreate(Sender: TObject);
begin
  RotImage := TBitmap.Create;
  RotAngle := 0;
end;

procedure TForm1.Button1Click(Sender: TObject);
var XIndex,
    YIndex,
    TargetWidth,
    TargetHeight,
    XTarget,
    YTarget      : Integer;
    SrcCanvas,
    DstCanvas    : TCanvas;
    SaveCursor   : TCursor;
begin
  SaveCursor := Screen.Cursor;
  Screen.Cursor := crHourGlass;
  Inc(RotAngle);
  if RotAngle = 4 // 360 degrees
   then RotAngle := 0; // 0 degrees
  if (RotAngle = 1) or (RotAngle = 3) then // 90 or 270 degrees
   begin
     TargetWidth := Image1.Picture.Bitmap.Height;
     TargetHeight := Image1.Picture.Bitmap.Width
   end
  else // 0 or 180 degrees
   begin
     TargetHeight := Image1.Picture.Bitmap.Height;
     TargetWidth := Image1.Picture.Bitmap.Width;
   end;
  RotImage.FreeImage;
  RotImage.Height := TargetHeight;
  RotImage.Width := TargetWidth;
  SrcCanvas := Image1.Picture.Bitmap.Canvas;
  DstCanvas := RotImage.Canvas;
  // step through pixels
  try
  for XIndex := 0 to Image1.Picture.Bitmap.Width - 1 do
   for YIndex := 0 to Image1.Picture.Bitmap.Height - 1 do
    begin
      if RotAngle = 0 then // 0 degrees
       begin
         XTarget := XIndex;
         YTarget := YIndex;
       end;
      if RotAngle = 1 then // 90 degrees
       begin
         XTarget := YIndex;
         YTarget := XIndex;
       end;
      if RotAngle = 2 then // 180 degrees
       begin
         XTarget := TargetWidth - XIndex - 1;
         YTarget := TargetHeight - YIndex - 1;
       end;
      if RotAngle = 3 then // 270 degrees
       begin
         XTarget := TargetWidth - YIndex - 1;
         YTarget := TargetHeight - XIndex - 1;
       end;
      DstCanvas.Pixels[XTarget, YTarget] := SrcCanvas.Pixels[XIndex, YIndex];
    end;
  Image2.Picture.Assign(RotImage);
  finally
    Screen.Cursor := SaveCursor;
  end;
end;

All you have to do is to code the images LoadFromFile and SaveToFile routines. Another thing not mentioned here is to pre-set the destination bitmaps palette (if it is palettized) to the source bitmaps palette.

Have fun,
Slash/d003303
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:Dippen
ID: 1351577
Odessa! I haven't got a clue what you're trying to say...

Heapster! I will take a look at question 306...

D003303! I tried your code and it worked, but what you mean by "quite fast" is a riddle to me :-). To rotate an image 800x600 pixels on my P75 took 2.15 minutes!!! That's NOT acceptable!

But even the simplest shareware-program can complete the same task in 2-3 seconds maximum. There must be some component/assembler source available that completes the task in that time!!

Any comments?


0
 

Author Comment

by:Dippen
ID: 1351578
OK...

Let's all agree that a rotation of an image that big (800x600 pixels) can't be done in Object Pascal. I tried the code in question 306 (309 nowadays) as well and it was to slow too.
Now I'm increasing the points hoping that anyone can guide me to a component or assembler source or whatever that can perform a 90/180/270 degree rotation of an TImage in less than 2 seconds. As I said before, every single image-handling program on the market can accomplish it in that time, so it's not impossible!?
0
 
LVL 1

Expert Comment

by:pjdb
ID: 1351579
One third of the solution (180 degrees) can be achieve with CopyRect :

source_rect.Top:=
source_rect.Bottom:=
source_rect.Left:=
source_rect.Right:=
dest_rect.Top:=source_rect.Top;
dest_rect.Bottom:=source_rect.Bottom;
dest_rect.Left:=source_rect.Left;
dest_rect.Right:=source_rect.Right;
moncanvas.CopyRect(dest_rect, travail.Canvas, source_rect);

Others require assembly, but don't know anything about this :-(
0
 
LVL 8

Expert Comment

by:ZifNab
ID: 1351580
Use CopyRect.... the easiest way

Use given formulas ...

Or use some freeware components ...

torry.rimini.com/vcl/graphics/rotatedimage.zip
torry.rimini.com/vcl/graphics/rotpic.zip

Regards Zif.
0
 
LVL 4

Expert Comment

by:d003303
ID: 1351581
Yo,
quite fast means that my code was optimized to reduce iterated method calls that take time, like assigning a Source and destination canvas as helper variables. I know that it is slow compared to assembler stuff. It should just give an idea on how it works.

Slash/d003303
0
 
LVL 4

Expert Comment

by:d003303
ID: 1351582
A quick question, should the app run on NT 4 only ? Then it would be quite simple.

Slash/d003303
0
 

Author Comment

by:Dippen
ID: 1351583
No, W95 or NT...
0
 
LVL 1

Expert Comment

by:michaue
ID: 1351584
Have you visited the TORI pages lately ...

Well I just saw to components by accident, because I don't work with images that much, but If they don't work I'm almost sure you will find something else you can use there ...
http://torry.rimini.com
I found the two components I mentioned under the "Expert Add-Onns & Property Editors" and under "Expert Add-Onns & Property Editors #3"
1.  Imagevue V 1.0.7
2. Olivier Dhan Glyph Property Editor V 1.1
Both of them is Freeware
Have fun, hope it helps
EM
0
 
LVL 4

Expert Comment

by:d003303
ID: 1351585
Yo,
the GetPixel and SetPixel API calls are the bottleneck. I'm nearly finished to get it run really FAST with my own routines. Hang on !

Slash/d003303
0
 

Author Comment

by:Dippen
ID: 1351586
Sorry, Michaue, I couldn't find any useful components for this purpose on the page you suggested. (The two components ZifNab suggested was too slow too.)

d003303: I'm eagerly waiting. If you could solve this I would be a very happy programmer!

//Dippen
0
 
LVL 4

Accepted Solution

by:
d003303 earned 200 total points
ID: 1351587
Yo,
here's the code. Included is a sample app. Load any bitmap into Image1, compile the app and play with the rotation.

unit Rotate;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ComCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    Image1: TImage;
    RadioGroup1: TRadioGroup;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

uses Math;

procedure RotateBitmap(ABitmap : TBitmap; RotAngle : Integer);
var XIndex,
    YIndex,
    XTarget,
    YTarget,
    SourceWidth,
    SourceHeight,
    TargetWidth,
    TargetHeight,
    CosAng,
    SinAng,
    PixelSizeStep : Integer;
    SrcMem,
    DstMem        : PByteArray;
    APixel        : array[0..4] of Byte;

 procedure GetPixel(X, Y : Integer);
 var Index, Helper : Integer;
 begin
  if PixelSizeStep = 4 then
   begin
     Helper := ((X - 1) div 2) + ((Y - 1) * SourceWidth div 2);
     if ((X - 1) mod 2) = 0
      then APixel[0] := ((15 shl 4) and (SrcMem[Helper])) shr 4
      else APixel[0] := 15 and SrcMem[Helper];
   end
  else
   begin
     for Index := 0 to (PixelSizeStep div 8) - 1 do
      begin
        Helper := (X - 1) * (PixelSizeStep div 8) + (Y - 1) * SourceWidth * (PixelSizeStep div 8) + Index;
        APixel[Index] := SrcMem[Helper];
      end;
   end;
 end;

 procedure SetPixel(X, Y : Integer);
 var Index, Helper : Integer;
 begin
  if PixelSizeStep = 4 then
   begin
     Helper := ((X - 1) div 2) + ((Y - 1) * TargetWidth div 2);
     if ((X - 1) mod 2) = 0
      then DstMem[Helper] := (DstMem[Helper] and 15) or (APixel[0] shl 4)
      else DstMem[Helper] := (DstMem[Helper] and (15 shl 4)) or APixel[0];
   end
  else
   begin
     for Index := 0 to (PixelSizeStep div 8) - 1 do
      begin
        Helper := (X - 1) * (PixelSizeStep div 8) + (Y - 1) * TargetWidth * (PixelSizeStep div 8) + Index;
        DstMem[Helper] := APixel[Index];
      end;
   end;
 end;

begin
  CosAng := Trunc(cos(DegToRad(RotAngle * 90)));
  SinAng := Trunc(sin(DegToRad(RotAngle * 90)));

  SourceWidth := ABitmap.Width;
  SourceHeight := ABitmap.Height;
  TargetWidth := Trunc(Abs(CosAng * SourceWidth + SinAng * SourceHeight));
  TargetHeight := Trunc(Abs(CosAng * SourceHeight + SinAng * SourceWidth));

  case ABitmap.PixelFormat of
    pf4bit  : PixelSizeStep := 4;
    pf8bit  : PixelSizeStep := 8;
    pf16bit : PixelSizeStep := 16;
    pf24bit : PixelSizeStep := 24;
    pf32bit : PixelSizeStep := 32;
    pf1bit,
    pf15bit : raise Exception.Create('Bitmap format not supported')
  end;

  SrcMem := ABitmap.ScanLine[SourceHeight - 1];
  GetMem(DstMem, TargetWidth * TargetHeight * PixelSizeStep div 8);
  try
    // clear bitmap
    FillChar(DstMem[0], TargetWidth * TargetHeight * PixelSizeStep div 8, $FF);
    // step through pixels
    for YIndex := 1 to SourceHeight do
     for XIndex := 1 to SourceWidth do
      begin
        GetPixel(XIndex, YIndex);
        XTarget := (XIndex * CosAng) - (YIndex * SinAng);
        YTarget := (XIndex * SinAng) + (YIndex * CosAng);
        if Abs(XTarget) <> XTarget
         then XTarget := XTarget + TargetWidth + 1;
        if Abs(YTarget) <> YTarget
         then YTarget := YTarget + TargetHeight + 1;
        SetPixel(XTarget, YTarget);
      end;
    ABitmap.Height := TargetHeight;
    ABitmap.Width := TargetWidth;
    SrcMem := ABitmap.ScanLine[TargetHeight - 1];
    move(DstMem[0], SrcMem[0], TargetWidth * TargetHeight * PixelSizeStep div 8);
  finally
    FreeMem(DstMem, TargetWidth * TargetHeight * PixelSizeStep div 8);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var SaveCursor : TCursor;
begin
  SaveCursor := Screen.Cursor;
  Screen.Cursor := crHourGlass;
  try
    RotateBitmap(Image1.Picture.Bitmap, RadioGroup1.ItemIndex);
  finally
    Image1.Refresh;
    Screen.Cursor := SaveCursor;
  end;
end;

end.

// form code

object Form1: TForm1
  Left = 214
  Top = 149
  Width = 384
  Height = 337
  Caption = 'Form1'
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  PixelsPerInch = 96
  TextHeight = 13
  object Image1: TImage
    Left = 4
    Top = 4
    Width = 269
    Height = 277
  end
  object RadioGroup1: TRadioGroup
    Left = 280
    Top = 4
    Width = 73
    Height = 117
    Caption = 'Angle'
    ItemIndex = 0
    Items.Strings = (
      '0'
      '90'
      '180'
      '270')
    TabOrder = 0
  end
  object Button1: TButton
    Left = 280
    Top = 124
    Width = 75
    Height = 25
    Caption = 'Rotate !'
    TabOrder = 1
    OnClick = Button1Click
  end
end

Have fun,
Slash/d003303
0
 

Author Comment

by:Dippen
ID: 1351588
Fabolous work, d003303! Thanks alot for the help!
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now