Каждый программист встречается с “Battle”. Иногда сидишь сутками, решая проблему и как прекрасен тот момент, когда понимаешь, как это можно решить.
Столкнулся с тем, что если загрузить методом idHTTP.Get jpg файл , у которого в exif данных указана ориентация, скажем “Rotate 90°”, то эта ориентация слетает, и это никак не вписывалось в мои планы. Хотелось нормальной ориентации)
Помучившись какое-то время с этим вопросом, я понял следующее.
1. Нужно научиться читать exif информацию
2. Нужно научиться поворачивать картинки, причем делать это быстро.
Определение ориентации
По 1 вопросу поиск дал отличнейший сайт. Это отличная библиотека для чтения exif информации. Скачав, установив все, я запустил демку. Вот как это выглядело.
Как видно ориентация у данной картинки нормальная и следовательно поворачивать её не нужно.
Следующие файлы я скопировал из скачанных файлов и положил их в папку, рядом с программой. Добавил это папку в lib самой delphi. Файл uBmpRot я создал сам – это код для поворота картинки.
Далее, нам понадобится такая функция, для приведения ориентации в человеческий вид.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
...uses ccr.exif const SUnrecognized = '[Unrecognised value (%d)]'; function OrientationToStr(Value: TTiffOrientation): string; begin case Value of toUndefined: Result := 'Undefined'; toTopLeft: Result := 'Normal'; toTopRight: Result := 'Mirror horizontal'; toBottomRight: Result := 'Rotate 180°'; toBottomLeft: Result := 'Mirror vertical'; toLeftTop: Result := 'Mirrow horizontal and rotate 270°'; toRightTop: Result := 'Rotate 90°'; toRightBottom: Result := 'Mirror hotizontal and rotate 90°'; toLeftBottom: Result := 'Rotate 270°'; else FmtStr(Result, SUnrecognized, [Ord(Value)]); end; end; |
Далее
1 2 3 4 5 |
... ExifData := TExifData.Create; ExifData.LoadFromGraphic(AbsWinFilePath); o:=OrientationToStr(ExifData.Orientation); ... |
Ну ок, определять ориентацию мы научились. Теперь нам нужно научиться поворачивать изображение.
Поворот Битмапа
На этом сайте я взял код для поворота битмапа и загнал его в юнит uBmpRot. Вот этот код
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 |
unit bmpRot; interface uses (*$IFDEF Win32*) Windows, (*$ELSE*) WinTypes, WinProcs, (*$ENDIF*) Classes, Graphics; procedure RotateBitmap90DegreesCounterClockwise(var ABitmap: TBitmap); procedure RotateBitmap90DegreesClockwise(var ABitmap: TBitmap); procedure RotateBitmap180Degrees(var ABitmap: TBitmap); implementation uses Dialogs; (*$IFNDEF Win32*) type DWORD = LongInt; TSelOfs = record L, H: Word; end; procedure Win16Dec(var P: Pointer; const N: LongInt); forward; procedure Win16Inc(var P: Pointer; const N: LongInt); begin if N < 0 then Win16Dec(P, -N) else if N > 0 then begin Inc( TSelOfs(P).H, TSelOfs(N).H * SelectorInc ); Inc( TSelOfs(P).L, TSelOfs(N).L ); if TSelOfs(P).L < TSelOfs(N).L then Inc( TSelOfs(P).H, SelectorInc ); end; end; procedure Win16Dec(var P: Pointer; const N: LongInt); begin if N < 0 then Win16Inc(P, -N) else if N > 0 then begin if TSelOfs(N).L > TSelOfs(P).L then Dec( TSelOfs(P).H, SelectorInc ); Dec( TSelOfs(P).L, TSelOfs(N).L ); Dec( TSelOfs(P).H, TSelOfs(N).H * SelectorInc ); end; end; (* procedure HugeShift; far; external 'KERNEL' index 113; procedure Win16Dec(var P: Pointer; const N: LongInt); forward; procedure Win16Inc(var HugePtr: Pointer; Amount: LongInt); procedure HugeInc; assembler; asm mov ax, Amount.Word[0] { Store Amount in DX:AX. } mov dx, Amount.Word[2] les bx, HugePtr { Get the reference to HugePtr. } add ax, es:[bx] { Add the offset parts. } adc dx, 0 { Propagate carry to the high word of Amount. } mov cx, Offset HugeShift shl dx, cl { Shift high word of Amount for segment. } add es:[bx+2], dx { Increment the segment of HugePtr. } mov es:[bx], ax end; begin if Amount > 0 then HugeInc else if Amount < 0 then Win16Dec(HugePtr, -Amount); end; procedure Win16Dec(var P: Pointer; const N: LongInt); begin if N < 0 then Win16Inc(P, -N) else if N > 0 then begin if TSelOfs(N).L > TSelOfs(P).L then Dec( TSelOfs(P).H, SelectorInc ); Dec( TSelOfs(P).L, TSelOfs(N).L ); Dec( TSelOfs(P).H, TSelOfs(N).H * SelectorInc ); end; end; *) (*$ENDIF*) procedure RotateBitmap90DegreesCounterClockwise(var ABitmap: TBitmap); const BitsPerByte = 8; var { A whole pile of variables. Some deal with one- and four-bit bitmaps only, some deal with eight- and 24-bit bitmaps only, and some deal with both. Any variable that ends in 'R' refers to the rotated bitmap, e.g. MemoryStream holds the original bitmap, and MemoryStreamR holds the rotated one. } PbmpInfoR: PBitmapInfoHeader; bmpBuffer, bmpBufferR: PByte; MemoryStream, MemoryStreamR: TMemoryStream; PbmpBuffer, PbmpBufferR: PByte; BytesPerPixel, PixelsPerByte: LongInt; BytesPerScanLine, BytesPerScanLineR: LongInt; PaddingBytes: LongInt; BitmapOffset: LongInt; BitCount: LongInt; WholeBytes, ExtraPixels: LongInt; SignificantBytes, SignificantBytesR: LongInt; ColumnBytes: LongInt; AtLeastEightBitColor: Boolean; T: LongInt; procedure NonIntegralByteRotate; (* nested *) { This routine rotates bitmaps with fewer than 8 bits of information per pixel, namely monochrome (1-bit) and 16-color (4-bit) bitmaps. Note that there are no such things as 2-bit bitmaps, though you might argue that Microsoft's bitmap format is worth about 2 bits. } var X, Y: LongInt; I: LongInt; MaskBits, CurrentBits: Byte; FirstMask, LastMask: Byte; PFirstScanLine: PByte; FirstIndex, CurrentBitIndex: LongInt; ShiftRightAmount, ShiftRightStart: LongInt; begin (*$IFDEF Win32*) Inc(PbmpBuffer, BytesPerScanLine * (PbmpInfoR^.biHeight - 1) ); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), BytesPerScanLine * (PbmpInfoR^.biHeight - 1) ); (*$ENDIF*) { PFirstScanLine advances along the first scan line of bmpBufferR. } PFirstScanLine := bmpBufferR; { Set up the indexing. } FirstIndex := BitsPerByte - BitCount; { Set up the bit masks: For a monochrome bitmap, LastMask := 00000001 and FirstMask := 10000000 For a 4-bit bitmap, LastMask := 00001111 and FirstMask := 11110000 We'll shift through these such that the CurrentBits and the MaskBits will go For a monochrome bitmap: 10000000, 01000000, 00100000, 00010000, 00001000, 00000100, 00000010, 00000001 For a 4-bit bitmap: 11110000, 00001111 The CurrentBitIndex denotes how far over the right-most bit would need to shift to get to the position of CurrentBits. For example, if we're on the eleventh column of a monochrome bitmap, then CurrentBits will equal 11 mod 8 := 3, or the 3rd-to-the-leftmost bit. Thus, the right-most bit would need to shift four places over to get anded correctly with CurrentBits. CurrentBitIndex will store this value. } LastMask := 1 shl BitCount - 1; FirstMask := LastMask shl FirstIndex; CurrentBits := FirstMask; CurrentBitIndex := FirstIndex; ShiftRightStart := BitCount * (PixelsPerByte - 1); { Here's the meat. Loop through the pixels and rotate appropriately. } { Remember that DIBs have their origins opposite from DDBs. } { The Y counter holds the current row of the source bitmap. } for Y := 1 to PbmpInfoR^.biHeight do begin PbmpBufferR := PFirstScanLine; { The X counter holds the current column of the source bitmap. We only deal with completely filled bytes here. Should there be an extra 'partial' byte, we'll deal with that below. } for X := 1 to WholeBytes do begin { Pick out the bits, starting with 10000000 for monochromes and 11110000 for 4-bit guys. } MaskBits := FirstMask; { ShiftRightAmount is the amount we need to shift the current bit all the way to the right. } ShiftRightAmount := ShiftRightStart; for I := 1 to PixelsPerByte do begin { Here's the doozy. Take the rotated bitmap's current byte and mask it with not CurrentBits. This zeros out the CurrentBits only, and leaves everything else unchanged. Example: For a monochrome bitmap, if we were on the 11th column as above, we would need to zero out the 3rd-to-left bit, so we would take PbmpBufferR^ and 11011111. Now consider our current source byte. For monochrome bitmaps, we're going to loop through each bit, for a total of eight pixels. For 4-bit bitmaps, we're going to loop through the bits four at a time, for a total of two pixels. Either way, we do this by masking it with MaskBits ('PbmpBuffer^ and MaskBits'). Now we need to get the bit(s) into the same column(s) that CurrentBits reflects. We do this by shifting them to the right-most part of the byte ('shr ShiftRightAmount'), and then shifting left by our aforementioned CurrentBitIndex ('shl CurrentBitIndex'). This is because, although a right-shift of -n should just be a left-shift of +n, it doesn't work that way, at least in Delphi. So we just start from scratch by putting everything as far right as we can. Finally, we have our source bit(s) shifted to the appropriate place, with nothing but zeros around. Simply or it with PbmpBufferR^ (which had its CurrentBits zeroed out, remember?) and we're done. Yeah, sure. "Simply". Duh. } PbmpBufferR^ := ( PbmpBufferR^ and not CurrentBits ) or ( (PbmpBuffer^ and MaskBits) shr ShiftRightAmount shl CurrentBitIndex ); { Move the MaskBits over for the next iteration. } MaskBits := MaskBits shr BitCount; (*$IFDEF Win32*) { Move our pointer to the rotated-bitmap buffer up one scan line. } Inc(PbmpBufferR, BytesPerScanLineR); { We don't need to shift as far to the right the next time around. } Dec(ShiftRightAmount, BitCount); (*$ELSE*) Win16Inc( Pointer(PbmpBufferR), BytesPerScanLineR ); Win16Dec( Pointer(ShiftRightAmount), BitCount ); (*$ENDIF*) end; (*$IFDEF Win32*) Inc(PbmpBuffer); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), 1 ); (*$ENDIF*) end; { If there's a partial byte, take care of it now. } if ExtraPixels <> 0 then begin { Do exactly the same crap as in the loop above. } MaskBits := FirstMask; ShiftRightAmount := ShiftRightStart; for I := 1 to ExtraPixels do begin PbmpBufferR^ := ( PbmpBufferR^ and not CurrentBits ) or ( (PbmpBuffer^ and MaskBits) shr ShiftRightAmount shl CurrentBitIndex ); MaskBits := MaskBits shr BitCount; (*$IFDEF Win32*) Inc(PbmpBufferR, BytesPerScanLineR); (*$ELSE*) Win16Inc( Pointer(PbmpBufferR), BytesPerScanLineR ); (*$ENDIF*) Dec(ShiftRightAmount, BitCount); end; (*$IFDEF Win32*) Inc(PbmpBuffer); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), 1 ); (*$ENDIF*) end; (*$IFDEF Win32*) { Skip the padding. } Inc(PbmpBuffer, PaddingBytes); { Back up the scan line you just traversed, and go one more to get set for the next row. } Dec(PbmpBuffer, BytesPerScanLine shl 1); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), PaddingBytes ); Win16Dec( Pointer(PbmpBuffer), BytesPerScanLine shl 1 ); (*$ENDIF*) if CurrentBits = LastMask then begin { We're at the end of this byte. Start over on another column. } CurrentBits := FirstMask; CurrentBitIndex := FirstIndex; { Go to the bottom of the rotated bitmap's column, but one column over. } (*$IFDEF Win32*) Inc(PFirstScanLine); (*$ELSE*) Win16Inc( Pointer(PFirstScanLine), 1 ); (*$ENDIF*) end else begin { Continue filling this byte. } CurrentBits := CurrentBits shr BitCount; Dec(CurrentBitIndex, BitCount); end; end; end; { procedure NonIntegralByteRotate (* nested *) } procedure IntegralByteRotate; (* nested *) var X, Y: LongInt; (*$IFNDEF Win32*) I: Integer; (*$ENDIF*) begin { Advance PbmpBufferR to the last column of the first scan line of bmpBufferR. } (*$IFDEF Win32*) Inc(PbmpBufferR, SignificantBytesR - BytesPerPixel); (*$ELSE*) Win16Inc( Pointer(PbmpBufferR), SignificantBytesR - BytesPerPixel ); (*$ENDIF*) { Here's the meat. Loop through the pixels and rotate appropriately. } { Remember that DIBs have their origins opposite from DDBs. } for Y := 1 to PbmpInfoR^.biHeight do begin for X := 1 to PbmpInfoR^.biWidth do begin { Copy the pixels. } (*$IFDEF Win32*) Move(PbmpBuffer^, PbmpBufferR^, BytesPerPixel); Inc(PbmpBuffer, BytesPerPixel); Inc(PbmpBufferR, BytesPerScanLineR); (*$ELSE*) for I := 1 to BytesPerPixel do begin PbmpBufferR^ := PbmpBuffer^; Win16Inc( Pointer(PbmpBuffer), 1 ); Win16Inc( Pointer(PbmpBufferR), 1 ); end; Win16Inc( Pointer(PbmpBufferR), BytesPerScanLineR - BytesPerPixel); (*$ENDIF*) end; (*$IFDEF Win32*) { Skip the padding. } Inc(PbmpBuffer, PaddingBytes); { Go to the top of the rotated bitmap's column, but one column over. } Dec(PbmpBufferR, ColumnBytes + BytesPerPixel); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), PaddingBytes); Win16Dec( Pointer(PbmpBufferR), ColumnBytes + BytesPerPixel); (*$ENDIF*) end; end; { This is the body of procedure RotateBitmap90DegreesCounterClockwise. } begin { Don't *ever* call GetDIBSizes! It screws up your bitmap. } MemoryStream := TMemoryStream.Create; { To do: Set the size before-hand. This will eliminate ReAlloc overhead for the MemoryStream. Calling GetDIBSizes would be nice, but, as mentioned above, it corrupts the Bitmap in some cases. Some API calls will probably take care of things, but I'm not going to mess with it right now. } { An undocumented method. Nice to have around, though. } ABitmap.SaveToStream(MemoryStream); { Don't need you anymore. We'll make a new one when the time comes. } ABitmap.Free; bmpBuffer := MemoryStream.Memory; { Get the offset bits. This may or may not include palette information. } BitmapOffset := PBitmapFileHeader(bmpBuffer)^.bfOffBits; { Set PbmpInfoR to point to the source bitmap's info header. } { Boy, these headers are getting annoying. } (*$IFDEF Win32*) Inc( bmpBuffer, SizeOf(TBitmapFileHeader) ); (*$ELSE*) Win16Inc( Pointer(bmpBuffer), SizeOf(TBitmapFileHeader) ); (*$ENDIF*) PbmpInfoR := PBitmapInfoHeader(bmpBuffer); { Set bmpBuffer and PbmpBuffer to point to the original bitmap bits. } bmpBuffer := MemoryStream.Memory; (*$IFDEF Win32*) Inc(bmpBuffer, BitmapOffset); (*$ELSE*) Win16Inc( Pointer(bmpBuffer), BitmapOffset ); (*$ENDIF*) PbmpBuffer := bmpBuffer; { Note that we don't need to worry about version 4 vs. version 3 bitmaps, because the fields we use -- namely biWidth, biHeight, and biBitCount -- occur in exactly the same place in both structs. So we're a bit lucky. OS/2 bitmaps, by the way, cause this to crash heinously. Sorry. } with PbmpInfoR^ do begin { ShowMessage('Compression := ' + IntToStr(biCompression)); } BitCount := biBitCount; { ShowMessage('BitCount := ' + IntToStr(BitCount)); } { ScanLines are DWORD aligned. } BytesPerScanLine := ((((biWidth * BitCount) + 31) div 32) * SizeOf(DWORD)); BytesPerScanLineR := ((((biHeight * BitCount) + 31) div 32) * SizeOf(DWORD)); AtLeastEightBitColor := BitCount >= BitsPerByte; if AtLeastEightBitColor then begin { Don't have to worry about bit-twiddling. Cool. } BytesPerPixel := biBitCount shr 3; SignificantBytes := biWidth * BitCount shr 3; SignificantBytesR := biHeight * BitCount shr 3; { Extra bytes required for DWORD aligning. } PaddingBytes := BytesPerScanLine - SignificantBytes; ColumnBytes := BytesPerScanLineR * biWidth; end else begin { One- or four-bit bitmap. Ugh. } PixelsPerByte := SizeOf(Byte) * BitsPerByte div BitCount; { The number of bytes entirely filled with pixel information. } WholeBytes := biWidth div PixelsPerByte; { Any extra bits that might partially fill a byte. For instance, a monochrome bitmap that is 14 pixels wide has one whole byte and a partial byte which has six bits actually used (the rest are garbage). } ExtraPixels := biWidth mod PixelsPerByte; { The number of extra bytes -- if any -- required to DWORD-align a scanline. } PaddingBytes := BytesPerScanLine - WholeBytes; { If there are extra bits (i.e., they run over into a 'partial byte'), then one of the padding bytes has already been accounted for. } if ExtraPixels <> 0 then Dec(PaddingBytes); end; { if AtLeastEightBitColor then } { The TMemoryStream that will hold the rotated bits. } MemoryStreamR := TMemoryStream.Create; { Set size for rotated bitmap. Might be different from source size due to DWORD aligning. } MemoryStreamR.SetSize(BitmapOffset + BytesPerScanLineR * biWidth); end; { with PbmpInfoR^ do } { Copy the headers from the source bitmap. } MemoryStream.Seek(0, soFromBeginning); MemoryStreamR.CopyFrom(MemoryStream, BitmapOffset); { Here's the buffer we're going to rotate. } bmpBufferR := MemoryStreamR.Memory; { Skip the headers, yadda yadda yadda... } (*$IFDEF Win32*) Inc(bmpBufferR, BitmapOffset); (*$ELSE*) Win16Inc( Pointer(bmpBufferR), BitmapOffset ); (*$ENDIF*) PbmpBufferR := bmpBufferR; { Do it. } if AtLeastEightBitColor then IntegralByteRotate else NonIntegralByteRotate; { Done with the source bits. } MemoryStream.Free; { Now set PbmpInfoR to point to the rotated bitmap's info header. } PbmpBufferR := MemoryStreamR.Memory; (*$IFDEF Win32*) Inc( PbmpBufferR, SizeOf(TBitmapFileHeader) ); (*$ELSE*) Win16Inc( Pointer(PbmpBufferR), SizeOf(TBitmapFileHeader) ); (*$ENDIF*) PbmpInfoR := PBitmapInfoHeader(PbmpBufferR); { Swap the width and height of the rotated bitmap's info header. } with PbmpInfoR^ do begin T := biHeight; biHeight := biWidth; biWidth := T; biSizeImage := 0; end; ABitmap := TBitmap.Create; { Spin back to the very beginning. } MemoryStreamR.Seek(0, soFromBeginning); { Load it back into ABitmap. } ABitmap.LoadFromStream(MemoryStreamR); MemoryStreamR.Free; end; procedure RotateBitmap90DegreesClockwise(var ABitmap: TBitmap); const BitsPerByte = 8; var { A whole pile of variables. Some deal with one- and four-bit bitmaps only, some deal with eight- and 24-bit bitmaps only, and some deal with both. Any variable that ends in 'R' refers to the rotated bitmap, e.g. MemoryStream holds the original bitmap, and MemoryStreamR holds the rotated one. } PbmpInfoR: PBitmapInfoHeader; bmpBuffer, bmpBufferR: PByte; MemoryStream, MemoryStreamR: TMemoryStream; PbmpBuffer, PbmpBufferR: PByte; BytesPerPixel, PixelsPerByte: LongInt; BytesPerScanLine, BytesPerScanLineR: LongInt; PaddingBytes: LongInt; BitmapOffset: LongInt; BitCount: LongInt; WholeBytes, ExtraPixels: LongInt; SignificantBytes: LongInt; ColumnBytes: LongInt; AtLeastEightBitColor: Boolean; T: LongInt; procedure NonIntegralByteRotate; (* nested *) { This routine rotates bitmaps with fewer than 8 bits of information per pixel, namely monochrome (1-bit) and 16-color (4-bit) bitmaps. Note that there are no such things as 2-bit bitmaps, though you might argue that Microsoft's bitmap format is worth about 2 bits. } var X, Y: LongInt; I: LongInt; MaskBits, CurrentBits: Byte; FirstMask, LastMask: Byte; PLastScanLine: PByte; FirstIndex, CurrentBitIndex: LongInt; ShiftRightAmount, ShiftRightStart: LongInt; begin { Advance PLastScanLine to the first column of the last scan line of bmpBufferR. } PLastScanLine := bmpBufferR; (*$IFDEF Win32*) Inc(PLastScanLine, BytesPerScanLineR * (PbmpInfoR^.biWidth - 1) ); (*$ELSE*) Win16Inc( Pointer(PLastScanLine), BytesPerScanLineR * (PbmpInfoR^.biWidth - 1) ); (*$ENDIF*) { Set up the indexing. } FirstIndex := BitsPerByte - BitCount; { Set up the bit masks: For a monochrome bitmap, LastMask := 00000001 and FirstMask := 10000000 For a 4-bit bitmap, LastMask := 00001111 and FirstMask := 11110000 We'll shift through these such that the CurrentBits and the MaskBits will go For a monochrome bitmap: 10000000, 01000000, 00100000, 00010000, 00001000, 00000100, 00000010, 00000001 For a 4-bit bitmap: 11110000, 00001111 The CurrentBitIndex denotes how far over the right-most bit would need to shift to get to the position of CurrentBits. For example, if we're on the eleventh column of a monochrome bitmap, then CurrentBits will equal 11 mod 8 := 3, or the 3rd-to-the-leftmost bit. Thus, the right-most bit would need to shift four places over to get anded correctly with CurrentBits. CurrentBitIndex will store this value. } LastMask := 1 shl BitCount - 1; FirstMask := LastMask shl FirstIndex; CurrentBits := FirstMask; CurrentBitIndex := FirstIndex; ShiftRightStart := BitCount * (PixelsPerByte - 1); { Here's the meat. Loop through the pixels and rotate appropriately. } { Remember that DIBs have their origins opposite from DDBs. } { The Y counter holds the current row of the source bitmap. } for Y := 1 to PbmpInfoR^.biHeight do begin PbmpBufferR := PLastScanLine; { The X counter holds the current column of the source bitmap. We only deal with completely filled bytes here. Should there be an extra 'partial' byte, we'll deal with that below. } for X := 1 to WholeBytes do begin { Pick out the bits, starting with 10000000 for monochromes and 11110000 for 4-bit guys. } MaskBits := FirstMask; { ShiftRightAmount is the amount we need to shift the current bit all the way to the right. } ShiftRightAmount := ShiftRightStart; for I := 1 to PixelsPerByte do begin { Here's the doozy. Take the rotated bitmap's current byte and mask it with not CurrentBits. This zeros out the CurrentBits only, and leaves everything else unchanged. Example: For a monochrome bitmap, if we were on the 11th column as above, we would need to zero out the 3rd-to-left bit, so we would take PbmpBufferR^ and 11011111. Now consider our current source byte. For monochrome bitmaps, we're going to loop through each bit, for a total of eight pixels. For 4-bit bitmaps, we're going to loop through the bits four at a time, for a total of two pixels. Either way, we do this by masking it with MaskBits ('PbmpBuffer^ and MaskBits'). Now we need to get the bit(s) into the same column(s) that CurrentBits reflects. We do this by shifting them to the right-most part of the byte ('shr ShiftRightAmount'), and then shifting left by our aforementioned CurrentBitIndex ('shl CurrentBitIndex'). This is because, although a right-shift of -n should just be a left-shift of +n, it doesn't work that way, at least in Delphi. So we just start from scratch by putting everything as far right as we can. Finally, we have our source bit(s) shifted to the appropriate place, with nothing but zeros around. Simply or it with PbmpBufferR^ (which had its CurrentBits zeroed out, remember?) and we're done. Yeah, sure. "Simply". Duh. } PbmpBufferR^ := ( PbmpBufferR^ and not CurrentBits ) or ( (PbmpBuffer^ and MaskBits) shr ShiftRightAmount shl CurrentBitIndex ); { Move the MaskBits over for the next iteration. } MaskBits := MaskBits shr BitCount; (*$IFDEF Win32*) { Move our pointer to the rotated-bitmap buffer up one scan line. } Dec(PbmpBufferR, BytesPerScanLineR); (*$ELSE*) Win16Dec( Pointer(PbmpBufferR), BytesPerScanLineR ); (*$ENDIF*) { We don't need to shift as far to the right the next time around. } Dec(ShiftRightAmount, BitCount); end; (*$IFDEF Win32*) Inc(PbmpBuffer); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), 1 ); (*$ENDIF*) end; { If there's a partial byte, take care of it now. } if ExtraPixels <> 0 then begin { Do exactly the same crap as in the loop above. } MaskBits := FirstMask; ShiftRightAmount := ShiftRightStart; for I := 1 to ExtraPixels do begin PbmpBufferR^ := ( PbmpBufferR^ and not CurrentBits ) or ( (PbmpBuffer^ and MaskBits) shr ShiftRightAmount shl CurrentBitIndex ); MaskBits := MaskBits shr BitCount; (*$IFDEF Win32*) Dec(PbmpBufferR, BytesPerScanLineR); (*$ELSE*) Win16Dec( Pointer(PbmpBufferR), BytesPerScanLineR ); (*$ENDIF*) Dec(ShiftRightAmount, BitCount); end; (*$IFDEF Win32*) Inc(PbmpBuffer); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), 1 ); (*$ENDIF*) end; { Skip the padding. } (*$IFDEF Win32*) Inc(PbmpBuffer, PaddingBytes); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), PaddingBytes ); (*$ENDIF*) if CurrentBits = LastMask then begin { We're at the end of this byte. Start over on another column. } CurrentBits := FirstMask; CurrentBitIndex := FirstIndex; { Go to the bottom of the rotated bitmap's column, but one column over. } (*$IFDEF Win32*) Inc(PLastScanLine); (*$ELSE*) Win16Inc( Pointer(PLastScanLine), 1 ); (*$ENDIF*) end else begin { Continue filling this byte. } CurrentBits := CurrentBits shr BitCount; Dec(CurrentBitIndex, BitCount); end; end; end; { procedure NonIntegralByteRotate (* nested *) } procedure IntegralByteRotate; (* nested *) var X, Y: LongInt; (*$IFNDEF Win32*) I: Integer; (*$ENDIF*) begin { Advance PbmpBufferR to the first column of the last scan line of bmpBufferR. } (*$IFDEF Win32*) Inc( PbmpBufferR, BytesPerScanLineR * (PbmpInfoR^.biWidth - 1) ); (*$ELSE*) Win16Inc( Pointer(PbmpBufferR) , BytesPerScanLineR * (PbmpInfoR^.biWidth - 1) ); (*$ENDIF*) { Here's the meat. Loop through the pixels and rotate appropriately. } { Remember that DIBs have their origins opposite from DDBs. } for Y := 1 to PbmpInfoR^.biHeight do begin for X := 1 to PbmpInfoR^.biWidth do begin { Copy the pixels. } (*$IFDEF Win32*) Move(PbmpBuffer^, PbmpBufferR^, BytesPerPixel); Inc(PbmpBuffer, BytesPerPixel); Dec(PbmpBufferR, BytesPerScanLineR); (*$ELSE*) for I := 1 to BytesPerPixel do begin PbmpBufferR^ := PbmpBuffer^; Win16Inc( Pointer(PbmpBuffer), 1 ); Win16Inc( Pointer(PbmpBufferR), 1 ); end; Win16Dec( Pointer(PbmpBufferR), BytesPerScanLineR + BytesPerPixel); (*$ENDIF*) end; (*$IFDEF Win32*) { Skip the padding. } Inc(PbmpBuffer, PaddingBytes); { Go to the top of the rotated bitmap's column, but one column over. } Inc(PbmpBufferR, ColumnBytes + BytesPerPixel); (*$ELSE*) Win16Inc( Pointer(PbmpBuffer), PaddingBytes ); Win16Inc( Pointer(PbmpBufferR), ColumnBytes + BytesPerPixel ); (*$ENDIF*) end; end; { This is the body of procedure RotateBitmap90DegreesCounterClockwise. } begin { Don't *ever* call GetDIBSizes! It screws up your bitmap. } MemoryStream := TMemoryStream.Create; { To do: Set the size before-hand. This will eliminate ReAlloc overhead for the MemoryStream. Calling GetDIBSizes would be nice, but, as mentioned above, it corrupts the Bitmap in some cases. Some API calls will probably take care of things, but I'm not going to mess with it right now. } { An undocumented method. Nice to have around, though. } ABitmap.SaveToStream(MemoryStream); { Don't need you anymore. We'll make a new one when the time comes. } ABitmap.Free; bmpBuffer := MemoryStream.Memory; { Get the offset bits. This may or may not include palette information. } BitmapOffset := PBitmapFileHeader(bmpBuffer)^.bfOffBits; { Set PbmpInfoR to point to the source bitmap's info header. } { Boy, these headers are getting annoying. } (*$IFDEF Win32*) Inc( bmpBuffer, SizeOf(TBitmapFileHeader) ); (*$ELSE*) Win16Inc( Pointer(bmpBuffer), SizeOf(TBitmapFileHeader) ); (*$ENDIF*) PbmpInfoR := PBitmapInfoHeader(bmpBuffer); { Set bmpBuffer and PbmpBuffer to point to the original bitmap bits. } bmpBuffer := MemoryStream.Memory; (*$IFDEF Win32*) Inc(bmpBuffer, BitmapOffset); (*$ELSE*) Win16Inc( Pointer(bmpBuffer), BitmapOffset ); (*$ENDIF*) PbmpBuffer := bmpBuffer; { Note that we don't need to worry about version 4 vs. version 3 bitmaps, because the fields we use -- namely biWidth, biHeight, and biBitCount -- occur in exactly the same place in both structs. So we're a bit lucky. OS/2 bitmaps, by the way, cause this to crash heinously. Sorry. } with PbmpInfoR^ do begin { ShowMessage('Compression := ' + IntToStr(biCompression)); } BitCount := biBitCount; { ShowMessage('BitCount := ' + IntToStr(BitCount)); } { ScanLines are DWORD aligned. } BytesPerScanLine := ((((biWidth * BitCount) + 31) div 32) * SizeOf(DWORD)); BytesPerScanLineR := ((((biHeight * BitCount) + 31) div 32) * SizeOf(DWORD)); AtLeastEightBitColor := BitCount >= BitsPerByte; if AtLeastEightBitColor then begin { Don't have to worry about bit-twiddling. Cool. } BytesPerPixel := biBitCount shr 3; SignificantBytes := biWidth * BitCount shr 3; { Extra bytes required for DWORD aligning. } PaddingBytes := BytesPerScanLine - SignificantBytes; ColumnBytes := BytesPerScanLineR * biWidth; end else begin { One- or four-bit bitmap. Ugh. } PixelsPerByte := SizeOf(Byte) * BitsPerByte div BitCount; { The number of bytes entirely filled with pixel information. } WholeBytes := biWidth div PixelsPerByte; { Any extra bits that might partially fill a byte. For instance, a monochrome bitmap that is 14 pixels wide has one whole byte and a partial byte which has six bits actually used (the rest are garbage). } ExtraPixels := biWidth mod PixelsPerByte; { The number of extra bytes -- if any -- required to DWORD-align a scanline. } PaddingBytes := BytesPerScanLine - WholeBytes; { If there are extra bits (i.e., they run over into a 'partial byte'), then one of the padding bytes has already been accounted for. } if ExtraPixels <> 0 then Dec(PaddingBytes); end; { if AtLeastEightBitColor then } { The TMemoryStream that will hold the rotated bits. } MemoryStreamR := TMemoryStream.Create; { Set size for rotated bitmap. Might be different from source size due to DWORD aligning. } MemoryStreamR.SetSize(BitmapOffset + BytesPerScanLineR * biWidth); end; { with PbmpInfoR^ do } { Copy the headers from the source bitmap. } MemoryStream.Seek(0, soFromBeginning); MemoryStreamR.CopyFrom(MemoryStream, BitmapOffset); { Here's the buffer we're going to rotate. } bmpBufferR := MemoryStreamR.Memory; { Skip the headers, yadda yadda yadda... } (*$IFDEF Win32*) Inc(bmpBufferR, BitmapOffset); (*$ELSE*) Win16Inc( Pointer(bmpBufferR), BitmapOffset ); (*$ENDIF*) PbmpBufferR := bmpBufferR; { Do it. } if AtLeastEightBitColor then IntegralByteRotate else NonIntegralByteRotate; { Done with the source bits. } MemoryStream.Free; { Now set PbmpInfoR to point to the rotated bitmap's info header. } PbmpBufferR := MemoryStreamR.Memory; (*$IFDEF Win32*) Inc( PbmpBufferR, SizeOf(TBitmapFileHeader) ); (*$ELSE*) Win16Inc( Pointer(PbmpBufferR), SizeOf(TBitmapFileHeader) ); (*$ENDIF*) PbmpInfoR := PBitmapInfoHeader(PbmpBufferR); { Swap the width and height of the rotated bitmap's info header. } with PbmpInfoR^ do begin T := biHeight; biHeight := biWidth; biWidth := T; biSizeImage := 0; end; ABitmap := TBitmap.Create; { Spin back to the very beginning. } MemoryStreamR.Seek(0, soFromBeginning); { Load it back into ABitmap. } ABitmap.LoadFromStream(MemoryStreamR); MemoryStreamR.Free; end; procedure RotateBitmap180Degrees(var ABitmap: TBitmap); var RotatedBitmap: TBitmap; begin RotatedBitmap := TBitmap.Create; with RotatedBitmap do begin Width := ABitmap.Width; Height := ABitmap.Height; Canvas.StretchDraw( Rect(ABitmap.Width, ABitmap.Height, 0, 0), ABitmap ); end; ABitmap.Free; ABitmap := RotatedBitmap; end; end. |
Конечное решение
Собрав всё вместе, мы получим что-то вроде…
1 2 3 4 5 6 7 8 9 |
if o='Rotate 90°' then RotateBitmap90DegreesClockwise(FBitmapDownLoaded) else if o='Rotate 180°' then begin RotateBitmap180Degrees(FBitmapDownLoaded); end else if o='Rotate 270°' then begin RotateBitmap180Degrees(FBitmapDownLoaded); RotateBitmap90DegreesClockwise(FBitmapDownLoaded); end; |
Вот в принципе и всё! Но для меня это были сутки мучений) Всем удачи…