Меню сайта
Категории раздела
Простые примеры [34] |
OpenGL [4] |
Фрактал [9] |
Windows API [2] |
Консоль [12] |
ДРУЗЬЯ САЙТА
Вызвать мастера в Красноярске
8 983 207 5474
8 902 918 9334
8 933 332 3164
---------------------------------
Запчасти бытткхники
Радиодетали
Электрика
ЗАКЛАДКИ
Поиск
Статистика
Онлайн всего: 3
Гостей: 3
Пользователей: 0
Главная » Статьи » C++ Builder » Простые примеры |
C++ BUILDER XE2 МЕНЯЕМ РАЗМЕР ФОТОГРАФИЙ
==================================== ========================================== //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <math.h> #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //-------------------------------------------------- void __fastcall TForm1::FormCreate(TObject *Sender) { //создаем объекты myjpg = new TJPEGImage; mypng = new TPngImage; mygif = new TGIFImage; Pic = new TPicture;// DirectoryListBox2->Directory = "C:\\"; //так тоже можно Edit3->Text = Kf = 1; } //--------------------------------------------------------------------------- void __fastcall TForm1::FormDestroy(TObject *Sender) { //освобождаем память в последовательности: последний создан первый удален delete Pic; delete mygif; delete mypng; delete myjpg; } //--------------------------------------------------------------------------- void __fastcall TForm1::FileListBox1Click(TObject *Sender) { //загружаем картинку if(FileListBox1->ItemIndex > -1 ){ Image1->Picture->LoadFromFile(FileListBox1->FileName); //полный путь до картинки Put = FileListBox1->FileName; //узнаем имя файла с расширением filename = ExtractFileName( FileListBox1->FileName ); //только имя файла расширение отрезаем ComboBox2->Text = filename.SubString(1, filename.Pos(".") - 1 ) ; //узнаем расширение ext = ExtractFileExt( FileListBox1->FileName ); //расширение в нижний регистр ComboBox1->Text = ext.LowerCase() ; //размеры картинки Widths = Image1->Picture->Width; Heights = Image1->Picture->Height; //новые размеры картинки в поля для редактирования для уменьшения //телодвижений при работе с кучей картинок одинаковых размеров Edit1->Text = static_cast<int>(Widths / Kf); Edit2->Text = static_cast<int>(Heights / Kf); //узнаем вес картинки в килобайтах TSearchRec SR ; float cb; if( FindFirst(FileListBox1->FileName, 0 , SR )==0 ){ cb = SR.Size ; cb = cb / 1024 ; } FindClose( SR ); Label1->Caption = " Ширина-" + IntToStr( Image1->Picture->Width ) + "p" + " Высота-" + IntToStr( Image1->Picture->Height ) + "p" + " Размер-" + FloatToStrF( cb, ffFixed, 10, 2 ) + "kb" ; Button4->Enabled = false; Panel5->Enabled = true; ScrollBox1Resize( this ); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button5Click(TObject *Sender) { //новый размер картинки if( Edit1->Text != "" && Edit2->Text != "" ) { int w = StrToInt(Edit1->Text); int h = StrToInt(Edit2->Text); //заполняем структуру rect непосредственно обращаясь к полям //rect.Left = 0; //rect.Top = 0; //rect.Right = w; //rect.Bottom = h; //заполняем структуру rect с помощью функй. SetRect проще // & - операция взятия адреса объекта rect возвращает указатель //для функции SetRect первый параметр указатель на структуру класса TRect SetRect( &rect, 0, 0,w, h ); //устанавливаем для Bitmap новые размеры Pic->Bitmap->Width = w; Pic->Bitmap->Height = h; //копируем в Bitmap Graphic Pic->Bitmap->Canvas->StretchDraw( rect, Image1->Picture->Graphic ); //отображаем в Image1 картинку с нов размерами Image1->Picture->Assign( Pic ); Button4->Enabled = true; ScrollBox1Resize( this ); } } //--------------------------------------------------------------------------- void __fastcall TForm1::DirectoryListBox2DblClick(TObject *Sender) { //путь к директории куда сохраняем filenams = DirectoryListBox2->GetItemPath( DirectoryListBox2->ItemIndex ) ; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button4Click(TObject *Sender) { //конвертируем в выбранный формат или оставляем исходный и сохраняем if( ComboBox2->Text != "" ) { if( ComboBox1->Text == ".png" ){ //могучий метод Assign копирует Bitmap в объект mypng mypng->Assign(Pic->Graphic) ; //объект mypng не только может сохранять в нужный формат но и делает //многое другое смотри его методы и свойства mypng->SaveToFile( filenams + "\\" + ComboBox2->Text + ComboBox1->Text ); } if( ComboBox1->Text == ".jpg" ){ myjpg->Assign(Pic->Graphic ) ; myjpg->SaveToFile( filenams + "\\" + ComboBox2->Text + ComboBox1->Text ); } if( ComboBox1->Text == ".gif" ){ mygif->Assign(Pic->Graphic); mygif->SaveToFile( filenams + "\\" + ComboBox2->Text + ComboBox1->Text ); } if( ComboBox1->Text == ".bmp" ){ Pic->Graphic->SaveToFile( filenams + "\\" + ComboBox2->Text + ComboBox1->Text ); } //что бы увидеть нов файл в окне FileListBox2 сделаем это FileListBox2->FileName = filenams; FileListBox2->Update(); //если в FileListBox2 открыта та же директория что и в FileListBox1 if( Put.Pos(filenams )>0){ FileListBox1->FileName = filenams; FileListBox1->Update(); } //добавляем имя файла в список (часто имена файлов имеют общий корень чтоб не набирать ) ComboBox2->Items->Add( ComboBox2->Text ) ; } } //--------------------------------------------------------------------------- void __fastcall TForm1::N1Click(TObject *Sender) { //истинный размер Image1->Align = alNone; Image1->Stretch = false; Image1->AutoSize = true; ScrollBox1Resize( this ); } //--------------------------------------------------------------------------- void __fastcall TForm1::N2Click(TObject *Sender) { //размер по окну Image1->Align = alClient; Image1->Stretch = true; Image1->AutoSize = false; ScrollBox1Resize( this ); } //--------------------------------------------------------------------------- void __fastcall TForm1::ComboBox1KeyPress(TObject *Sender, System::WideChar &Key) { //запрет ввода любых символов Key = 0; } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit1KeyPress(TObject *Sender, System::WideChar &Key) { //только целые числа if(Key >= '0' && Key <= '9' || Key == VK_BACK ) return; Key = 0; } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit1ContextPopup(TObject *Sender, TPoint &MousePos, bool &Handled) { //запрет контекстного меню Handled = true; } //------------------------------------------------------------------------ void __fastcall TForm1::Edit1Change(TObject *Sender) { //ввод ширины вычисление высоты и коэффициента if( CheckBox1->Checked && Edit1->Focused() ){ if( Edit1->Text == "" ) { Edit2->Text = ""; return; } Kf = Widths / Edit1->Text.ToDouble() ; Edit3->Text = FloatToStrF( Kf, ffFixed, 10, 4 ); Edit2->Text = static_cast<int>(Heights / Kf); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit2Change(TObject *Sender) { //ввод высоты вычисление ширины и коэффициента if( CheckBox1->Checked && Edit2->Focused() ){ if( Edit2->Text == "" ) { Edit1->Text = ""; return; } Kf = Heights / Edit2->Text.ToDouble() ; Edit3->Text = FloatToStrF( Kf, ffFixed, 10, 4 ); Edit1->Text = static_cast<int>(Widths / Kf); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit3Change(TObject *Sender) { //ввод коэффициента вычисление ширины и высоты if(CheckBox1->Checked && Edit3->Focused() ){ if(Edit3->Text == "" ) { return; } Kf = Edit3->Text.ToDouble(); if(Kf > 0){ Edit1->Text = static_cast<int>(Widths / Kf); Edit2->Text = static_cast<int>(Heights / Kf); } } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit3KeyPress(TObject *Sender, System::WideChar &Key) { //ввод коэффициента проверка на допустимые символы if( Key == ',' && Edit3->Text.Pos(",") > 0 ) { Key = 0; return; } if(Key >= '0' && Key <= '9' || Key == VK_BACK || Key == ',') return; Key = 0; } //--------------------------------------------------------------------------- void __fastcall TForm1::ScrollBox1Resize(TObject *Sender) { // Image1 по центру ScrollBox1 if( Image1->Width < ScrollBox1->ClientWidth ){ Image1->Left = ( ScrollBox1->ClientWidth - Image1->Width ) / 2; } else Image1->Left = 0; if( Image1->Height < ScrollBox1->ClientHeight ){ Image1->Top = ( ScrollBox1->ClientHeight - Image1->Height ) / 2; } else Image1->Top = 0; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #ifndef Unit1H #define Unit1H //--------------------------------------------------------------------------- #include <System.Classes.hpp> #include <Vcl.Controls.hpp> #include <Vcl.StdCtrls.hpp> #include <Vcl.Forms.hpp> #include <Vcl.Buttons.hpp> #include <Vcl.Dialogs.hpp> #include <Vcl.ExtCtrls.hpp> #include <Vcl.ExtDlgs.hpp> #include <Vcl.FileCtrl.hpp> #include <Vcl.Grids.hpp> #include <Vcl.Outline.hpp> #include <Vcl.Samples.DirOutln.hpp> //---------------------------------------------------------------------------- #include <Vcl.Imaging.jpeg.hpp> #include <Vcl.Imaging.GIFImg.hpp> #include <Vcl.Imaging.pngimage.hpp> #include <Vcl.Tabs.hpp> #include <Vcl.ComCtrls.hpp> #include <Vcl.Menus.hpp> //--------------------------------------------------------------------------- class TForm1 : public TForm { __published: // IDE-managed Components TImage *Image1; TScrollBox *ScrollBox1; TDriveComboBox *DriveComboBox1; TDirectoryListBox *DirectoryListBox1; TFileListBox *FileListBox1; TPanel *Panel1; TPanel *Panel2; TSplitter *Splitter1; TPanel *Panel3; TSplitter *Splitter2; TPanel *Panel4; TLabel *Label1; TPanel *Panel5; TEdit *Edit1; TEdit *Edit2; TButton *Button5; TButton *Button6; TPanel *Panel8; TPanel *Panel9; TSplitter *Splitter3; TPanel *Panel10; TDriveComboBox *DriveComboBox2; TDirectoryListBox *DirectoryListBox2; TFileListBox *FileListBox2; TPageControl *PageControl1; TTabSheet *TabSheet1; TComboBox *ComboBox1; TButton *Button4; TPopupMenu *PopupMenu1; TMenuItem *N1; TMenuItem *N2; TComboBox *ComboBox2; TCheckBox *CheckBox1; TPopupMenu *PopupMenu2; TEdit *Edit3; void __fastcall FileListBox1Click(TObject *Sender); void __fastcall FormDestroy(TObject *Sender); void __fastcall FormCreate(TObject *Sender); void __fastcall Button5Click(TObject *Sender); void __fastcall Edit1KeyPress(TObject *Sender, System::WideChar &Key); void __fastcall Edit1ContextPopup(TObject *Sender, TPoint &MousePos, bool &Handled); void __fastcall Button4Click(TObject *Sender); void __fastcall N1Click(TObject *Sender); void __fastcall N2Click(TObject *Sender); void __fastcall DirectoryListBox2DblClick(TObject *Sender); void __fastcall ComboBox1KeyPress(TObject *Sender, System::WideChar &Key); void __fastcall Edit1Change(TObject *Sender); void __fastcall Edit2Change(TObject *Sender); void __fastcall Edit3Change(TObject *Sender); void __fastcall Edit3KeyPress(TObject *Sender, System::WideChar &Key); void __fastcall ScrollBox1Resize(TObject *Sender); private: // User declarations public: // User declarations TPicture *Pic ;// TRect rect,rim; float Widths, Heights,Kf; UnicodeString filename,ext,filenams,Put; TJPEGImage *myjpg; TGIFImage *mygif; TPngImage *mypng; __fastcall TForm1(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TForm1 *Form1; //--------------------------------------------------------------------------- #endif ========================================================= | |
Просмотров: 3148 | Рейтинг: 0.0/0 |