Размещение JPG изображения на графике - страница 2

 
Murat Ishakov #:
А такое на mql4 возможно? Может есть пример конвертации на mql4 (любого файла)?
Murat Ishakov #:
Или где прочитать вообще про основы конвертации файлов?

Как я понял в C++ используют в основном библиотеку JPEG.CPP, вот один из примеров.

MQL язык умеет читать бинарные файлы - главное тут знать его структуру, я так понимаю, тут есть статья.

[Удален]  

Один из способов загрузки JPEGов при помощи WinAPI.

#define _WIN64  // Только для 64-разрядного терминала!

#include <WinDef.mqh>

#define HINSTANCE PVOID
#define LPCWSTR PVOID
#define LPWSTR PVOID
#define LPARAM PVOID
#define LPOFNHOOKPROC PVOID
#define UINT_PTR PVOID
#define GpBitmap PVOID
#define HRESULT uint
#define S_OK 0
#define PixelFormat int

#define _MAX_PATH   260 // max. length of full pathname
#define _MAX_FNAME  256 // max. length of file name component
#define _MAX_EXT    256 // max. length of extension component

#define OFN_FILEMUSTEXIST  0x00001000
#define OFN_HIDEREADONLY   0x00000004

#define    PixelFormatIndexed      0x00010000 // Indexes into a palette
#define    PixelFormatGDI          0x00020000 // Is a GDI-supported format
#define    PixelFormatAlpha        0x00040000 // Has an alpha component
#define    PixelFormatPAlpha       0x00080000 // Pre-multiplied alpha
#define    PixelFormatExtended     0x00100000 // Extended color 16 bits/channel
#define    PixelFormatCanonical    0x00200000 

#define    PixelFormatUndefined       0
#define    PixelFormatDontCare        0

#define    PixelFormat1bppIndexed     (1 | ( 1 << 8) | PixelFormatIndexed | PixelFormatGDI)
#define    PixelFormat4bppIndexed     (2 | ( 4 << 8) | PixelFormatIndexed | PixelFormatGDI)
#define    PixelFormat8bppIndexed     (3 | ( 8 << 8) | PixelFormatIndexed | PixelFormatGDI)
#define    PixelFormat16bppGrayScale  (4 | (16 << 8) | PixelFormatExtended)
#define    PixelFormat16bppRGB555     (5 | (16 << 8) | PixelFormatGDI)
#define    PixelFormat16bppRGB565     (6 | (16 << 8) | PixelFormatGDI)
#define    PixelFormat16bppARGB1555   (7 | (16 << 8) | PixelFormatAlpha | PixelFormatGDI)
#define    PixelFormat24bppRGB        (8 | (24 << 8) | PixelFormatGDI)
#define    PixelFormat32bppRGB        (9 | (32 << 8) | PixelFormatGDI)
#define    PixelFormat32bppARGB       (10 | (32 << 8) | PixelFormatAlpha | PixelFormatGDI | PixelFormatCanonical)
#define    PixelFormat32bppPARGB      (11 | (32 << 8) | PixelFormatAlpha | PixelFormatPAlpha | PixelFormatGDI)
#define    PixelFormat48bppRGB        (12 | (48 << 8) | PixelFormatExtended)
#define    PixelFormat64bppARGB       (13 | (64 << 8) | PixelFormatAlpha  | PixelFormatCanonical | PixelFormatExtended)
#define    PixelFormat64bppPARGB      (14 | (64 << 8) | PixelFormatAlpha  | PixelFormatPAlpha | PixelFormatExtended)
#define    PixelFormat32bppCMYK       (15 | (32 << 8))
#define    PixelFormatMax             16

enum GpStatus
{
   Ok = 0,
   GenericError = 1,
   InvalidParameter = 2,
   OutOfMemory = 3,
   ObjectBusy = 4,
   InsufficientBuffer = 5,
   NotImplemented = 6,
   Win32Error = 7,
   WrongState = 8,
   Aborted = 9,
   FileNotFound = 10,
   ValueOverflow = 11,
   AccessDenied = 12,
   UnknownImageFormat = 13,
   FontFamilyNotFound = 14,
   FontStyleNotFound = 15,
   NotTrueTypeFont = 16,
   UnsupportedGdiplusVersion = 17,
   GdiplusNotInitialized = 18,
   PropertyNotFound = 19,
   PropertyNotSupported = 20,
   ProfileNotFound = 21
};

struct OPENFILENAME pack( sizeof( PVOID ) )
{ 
   DWORD          lStructSize;
   HWND           hwndOwner;
   HINSTANCE      hInstance;
   LPCWSTR        lpstrFilter;
   LPWSTR         lpstrCustomFilter;
   DWORD          nMaxCustFilter;
   DWORD          nFilterIndex;
   LPWSTR         lpstrFile;
   DWORD          nMaxFile;
   LPWSTR         lpstrFileTitle;
   DWORD          nMaxFileTitle;
   LPCWSTR        lpstrInitialDir;
   LPCWSTR        lpstrTitle;
   DWORD          Flags;
   WORD           nFileOffset;
   WORD           nFileExtension;
   LPCWSTR        lpstrDefExt;
   LPARAM         lCustData;
   LPOFNHOOKPROC  lpfnHook;
   LPCWSTR        lpTemplateName;
   PVOID          pvReserved;
   DWORD          dwReserved;
   DWORD          FlagsEx;
};

struct GpRect
{
   uint X;
   uint Y;
   uint Width;
   uint Height;
};

struct BitmapData
{
   uint Width;
   uint Height;
   int Stride;
   PixelFormat pixelFormat;
   PVOID Scan0;
   UINT_PTR Reserved;
};

enum ImageLockMode {
  ImageLockModeRead = 0x0001,
  ImageLockModeWrite = 0x0002,
  ImageLockModeUserInputBuf = 0x0004
};

#import "comdlg32.dll"
   BOOL GetOpenFileNameW( OPENFILENAME& ofn );
   
#import "OleAut32.dll"
   HRESULT VarI4FromUI4( const ushort& var, uint& plOut );
   HRESULT VarI4FromUI4( const uint& var, uint& plOut );
   HRESULT VarI4FromUI4( const string& var, uint& plOut );
   HRESULT VarI8FromUI8( const ushort& var, ulong& plOut );
   HRESULT VarI8FromUI8( const uint& var, ulong& plOut );
   HRESULT VarI8FromUI8( const string& var, ulong& plOut );
   
#import "GdiPlus.dll"
   GpStatus GdipCreateBitmapFromFileICM( string fileName, GpBitmap& bitmap );
   GpStatus GdipGetImageWidth( GpBitmap bitmap, uint& width );
   GpStatus GdipGetImageHeight( GpBitmap bitmap, uint& height );
   GpStatus GdipBitmapLockBits( GpBitmap bitmap, GpRect& rect, UINT flags, PixelFormat format, BitmapData& lockedBitmapData );
   GpStatus GdipBitmapUnlockBits( GpBitmap bitmap, BitmapData& lockedBitmapData );
   GpStatus GdipDisposeImage( GpBitmap bitmap );
#import


//+-----------------------------------------------------------------------------------------------+
//| Script program start function                                                                 |
//+-----------------------------------------------------------------------------------------------+
void OnStart()
{
   string fileName;
   
   if( !OpenFileDialog( fileName ) ){
      return;
   }
   
   GpBitmap bitmap;
   GpStatus status = GdipCreateBitmapFromFileICM( fileName, bitmap );
   if( status == Ok ){
      uint width;
      uint height;
      GdipGetImageWidth( bitmap, width );
      GdipGetImageHeight( bitmap, height );
      
      uint dataSize = width * height;
      uint data[];
      ArrayResize( data, dataSize );
      
      GpRect rect = { 0, 0, width, height };
      
      BitmapData lockedBitmapData = {};
      
      lockedBitmapData.Width = width;
      lockedBitmapData.Height = height;
      lockedBitmapData.Stride = int(width * 4);
      lockedBitmapData.pixelFormat = PixelFormat32bppARGB;
      lockedBitmapData.Scan0 = AddressOf( data[0] );
      
      status = GdipBitmapLockBits( bitmap, rect, ImageLockModeRead|ImageLockModeUserInputBuf, PixelFormat32bppARGB, lockedBitmapData );
      
      GdipBitmapUnlockBits( bitmap, lockedBitmapData );
      
      GdipDisposeImage( bitmap );
      
      ResourceCreate( "Jpeg", data, width, height, 0, 0, width, COLOR_FORMAT_ARGB_NORMALIZE );
      
      string bitmapName = "Фон";
      ObjectCreate( 0, bitmapName, OBJ_BITMAP_LABEL, 0, 0, 0 );
      
      ObjectSetString( 0, bitmapName, OBJPROP_BMPFILE, 0, "::Jpeg" );
   }
}
//+-----------------------------------------------------------------------------------------------+
bool OpenFileDialog( string& fileName )
{
   wchar_t Buffer[_MAX_PATH];
   Buffer[0] = 0;
   
   string InitialDir = TerminalInfoString( TERMINAL_DATA_PATH ) + "\\MQL5\\Files";
   string Title = "Открыть JPEG файл";
   string filter = "JPEG files\0*.jpg;*.jpeg\0";
   
   OPENFILENAME ofn = {};
   ofn.lStructSize = sizeof( OPENFILENAME );
   ofn.hwndOwner              = ChartGetInteger( 0, CHART_WINDOW_HANDLE );
   ofn.lpstrFilter            = AddressOf( filter );
   ofn.nFilterIndex           = 1;
   ofn.lpstrFile              = AddressOf( Buffer[0] );
   ofn.nMaxFile               = _MAX_PATH;
   ofn.nMaxFileTitle          = _MAX_FNAME + _MAX_EXT;
   ofn.lpstrInitialDir        = AddressOf( InitialDir );
   ofn.lpstrTitle             = AddressOf( Title );
   ofn.Flags                  = OFN_FILEMUSTEXIST|OFN_HIDEREADONLY;
   
   if( GetOpenFileNameW( ofn ) == TRUE ){
      fileName = ShortArrayToString( Buffer );
      return true;
   }
   return false;
}
//+-----------------------------------------------------------------------------------------------+
template< typename Type >
PVOID AddressOf( const Type& data )
{
   PVOID lOut;
#ifdef _WIN64
   HRESULT result = VarI8FromUI8( data, lOut );
#else
   HRESULT result = VarI4FromUI4( data, lOut );
#endif
   if( result == S_OK ){
      return lOut;
   }
   return 0;
}
//+-----------------------------------------------------------------------------------------------+
Файлы:
WinDef.mqh  2 kb
LoadJpeg.mq5  18 kb
LoadJpeg.mq4  18 kb
 
Koldun Zloy #:

Один из способов загрузки JPEGов при помощи WinAPI.

Очень круто, спасибо!

Только сразу возникает вопрос, как менять размер картинки?

И, можно ли, нанести надпись на картинку и сохранить обратно на диск (желательно jpeg), можно даже без вывода изображения на экран?

Дело в том, что картинки больше чарта...

[Удален]  
Aleksey Vyazmikin #:

Очень круто, спасибо!

Только сразу возникает вопрос, как менять размер картинки?

И, можно ли, нанести надпись на картинку и сохранить обратно на диск (желательно jpeg), можно даже без вывода изображения на экран?

Дело в том, что картинки больше чарта...

Всё это возможно. И можно сделать разными способами.

я использовал библиотеку GDI+. Она может и менять размер, и наносить текст, и сохранять в файл, и много чего ещё.

Подробности здесь и здесь.

GDI+: графика нового поколения
  • rsdn.org
Обзор возможностей GDI+. Рекомендации по программированию. Первая программа.
 
Koldun Zloy #:

Всё это возможно. И можно сделать разными способами.

я использовал библиотеку GDI+. Она может и менять размер, и наносить текст, и сохранять в файл, и много чего ещё.

Подробности здесь и здесь.

Спасибо.