Club Builder - Foros de discusión Club Builder
Foro de C++Builder en español
 
 FAQFAQ   BuscarBuscar   MiembrosMiembros   Grupos de UsuariosGrupos de Usuarios   RegistrarseRegistrarse 
 PerfilPerfil   Entra para ver tus mensajes privadosEntra para ver tus mensajes privados   EntrarEntrar 

GDI+

 
Publicar nuevo tema   Responder al tema    Foros de discusión -> Consultas
Ver tema anterior :: Ver tema siguiente  
Autor Mensaje
Mensaje    Asunto: GDI+ Responder citando

Estoy realizando una rutina para grabar cualquier imagen en formato PNG
de echo la rutina funciona, graba en formato PNG, carga cualquier imagen, pero el problema es que no deja las imagenes optimizadas, si no que las aumenta de tamaño, el unico tamaño aceptables es cuando se guarda en formato GIF, pero con una pesima calidad.

Alguien ha tenido la fortuna de opitmizar el tamaño de un PNG a partir de otro archivo de imagen, pongo los codigos por si alguien le sirve y puede optimizarla
1.- Crean un nuevo proyecto en BCB y le agregan la ruta de los LIB donde esta la libreria Gdiplus.lib y Gdiplus.h

archivo . cpp
Código:
//---------------------------------------------------------------------------
#define STRICT

#include <vcl.h>
#include <stdio.h>
#pragma hdrstop

#include "UimagenesPNG.h"
#include <memory>

#include <Gdiplus.h>
#include <GdiPlusEnums.h>
using   namespace   Gdiplus;
#pragma comment(lib, "Gdiplus.lib") // poner la ruta dentro de las libreriras
using namespace Gdiplus;

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
   : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::cbImagenCompletaClick(TObject *Sender)
{
   this->image->Proportional = this->cbImagenCompleta->Checked;
   this->image->Align = this->image->Proportional ? alClient : alNone;

}
//---------------------------------------------------------------------------
void __fastcall TForm1::bAbrirClick(TObject *Sender)
{
   GdiplusStartup(&ccGdiplusToken, &ccGdiplusStartupInput, NULL);// init GDI+
   if(this->OpenDialog1->Execute())
   {

      const TCHAR* fileName = this->OpenDialog1->FileName.c_str();
      Gdiplus::Bitmap* pGdiBitmap = new Gdiplus::Bitmap(WideString(fileName),true);
      HBITMAP hBitmap;
      Gdiplus::Color clBackground = Gdiplus::Color(0, 0, 0);
      pGdiBitmap->GetHBITMAP( clBackground, &hBitmap);
      this->image->Picture->Bitmap->Handle  = hBitmap;
      delete pGdiBitmap;
   }
   GdiplusShutdown(ccGdiplusToken); // Close GDI+

}
//---------------------------------------------------------------------------
void __fastcall TForm1::bGrabarClick(TObject *Sender)
{
GdiplusStartup(&ccGdiplusToken, &ccGdiplusStartupInput, NULL);
   if(this->SaveDialog1->Execute(this->Handle))
   {

   CoInitialize(NULL);
      TMemoryStream * mem_p= new TMemoryStream();
      this->image->Picture->Graphic->SaveToStream(mem_p);
      mem_p->Seek(0,0);
      TStreamAdapter * streamadapter_p = new TStreamAdapter(mem_p, soReference);
      Gdiplus::Image *pGif = new Gdiplus::Image((IStream *)*streamadapter_p);

      // sacado de GdiplusImaging.h
      // linea No. 30, pero al parecer no es correcto.

     Gdiplus::EncoderParameters encoderParams;

     int quality = 100;
     encoderParams.Count = 1;
     encoderParams.Parameter[0].Guid           = EncoderTransformation;
     encoderParams.Parameter[0].Type           = EncoderParameterValueTypeLong;
     encoderParams.Parameter[0].NumberOfValues = 1;
     encoderParams.Parameter[0].Value          = &quality;

   CLSID clsidEncoder;
   GetEncoderClsid(L"image/png",&clsidEncoder);
   pGif->Save( WideString( this->SaveDialog1->FileName+".png").c_bstr() , &clsidEncoder, &encoderParams);

   GetEncoderClsid(L"image/jpeg",&clsidEncoder);
   pGif->Save( WideString( this->SaveDialog1->FileName+".jpg").c_bstr() , &clsidEncoder, &encoderParams);


   GetEncoderClsid(L"image/gif",&clsidEncoder);
   pGif->Save( WideString( this->SaveDialog1->FileName+".gif").c_bstr() , &clsidEncoder, &encoderParams);


   GetEncoderClsid(L"image/tiff",&clsidEncoder);
   pGif->Save( WideString( this->SaveDialog1->FileName+".tif").c_bstr() , &clsidEncoder, &encoderParams);

   GetEncoderClsid(L"image/bmp",&clsidEncoder);
   pGif->Save( WideString( this->SaveDialog1->FileName+".bmp").c_bstr() , &clsidEncoder, &encoderParams);

   CoUninitialize ();

   }
      GdiplusShutdown(ccGdiplusToken); // Close GDI+
}
//---------------------------------------------------------------------------
// esta funcion se ha sacado de la página de Microsoft, msdn
//http://msdn.microsoft.com/en-us/library/ms533843(VS.85).aspx

int __fastcall TForm1::GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
   UINT  num = 0;          // number of image encoders
   UINT  size = 0;         // size of the image encoder array in bytes

   ImageCodecInfo* pImageCodecInfo = NULL;

   GetImageEncodersSize(&num, &size);
   if(size == 0)
     return -1;  // Failure

   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
   if(pImageCodecInfo == NULL)
     return -1;  // Failure

   GetImageEncoders(num, size, pImageCodecInfo);

   for(UINT j = 0; j < num; ++j)
   {
     if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
     {
       *pClsid = pImageCodecInfo[j].Clsid;
       free(pImageCodecInfo);
       return j;  // Success
     }
   }
   free(pImageCodecInfo);
   return -1;  // Failure
}
//---------------------------------------------------------------------------

archivo .h
Código:

//---------------------------------------------------------------------------
#ifndef UimagenesPNGH
#define UimagenesPNGH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Dialogs.hpp>
#include <ExtCtrls.hpp>

#include "gdiplus.h"
using namespace Gdiplus;
#pragma comment(lib, "Gdiplus.lib")
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:   // IDE-managed Components
   TButton *bAbrir;
   TButton *bGrabar;
   TGroupBox *GroupBox1;
   TScrollBox *ScrollBox1;
   TImage *image;
   TCheckBox *cbImagenCompleta;
   TSaveDialog *SaveDialog1;
   TOpenDialog *OpenDialog1;
   void __fastcall cbImagenCompletaClick(TObject *Sender);
   void __fastcall bAbrirClick(TObject *Sender);
   void __fastcall bGrabarClick(TObject *Sender);
private:   // User declarations
   ULONG_PTR ccGdiplusToken;
   Gdiplus::GdiplusStartupInput ccGdiplusStartupInput;
   HDC    cchdcMemory;
   //  FUNCION PARA saber si esta instalado el formato, sacado de MSDN
   int __fastcall GetEncoderClsid(const WCHAR* format, CLSID* pClsid);
public:      // User declarations
   __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif



Archivo DFM
Código:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 590
  ClientWidth = 438
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object bAbrir: TButton
    Left = 23
    Top = 522
    Width = 75
    Height = 25
    Caption = 'Abrir Archivo'
    TabOrder = 0
    OnClick = bAbrirClick
  end
  object bGrabar: TButton
    Left = 125
    Top = 522
    Width = 75
    Height = 25
    Caption = 'Grabar Archivo'
    TabOrder = 1
    OnClick = bGrabarClick
  end
  object GroupBox1: TGroupBox
    Left = 0
    Top = 0
    Width = 438
    Height = 386
    Align = alTop
    BiDiMode = bdLeftToRight
    Color = clWhite
    ParentBackground = False
    ParentBiDiMode = False
    ParentColor = False
    TabOrder = 2
    object ScrollBox1: TScrollBox
      Left = 2
      Top = 15
      Width = 434
      Height = 369
      HorzScrollBar.Tracking = True
      VertScrollBar.Tracking = True
      Align = alClient
      BevelInner = bvNone
      BevelOuter = bvRaised
      BevelKind = bkSoft
      BorderStyle = bsNone
      Color = clWhite
      ParentColor = False
      TabOrder = 0
      object image: TImage
        Left = 0
        Top = 0
        Width = 432
        Height = 367
        Align = alClient
        AutoSize = True
        Center = True
        Proportional = True
        ExplicitLeft = -1
        ExplicitTop = 24
        ExplicitWidth = 252
        ExplicitHeight = 200
      end
    end
  end
  object cbImagenCompleta: TCheckBox
    Left = 285
    Top = 536
    Width = 125
    Height = 20
    Alignment = taLeftJustify
    BiDiMode = bdRightToLeft
    Caption = 'Vista Completa'
    Checked = True
    ParentBiDiMode = False
    State = cbChecked
    TabOrder = 3
    OnClick = cbImagenCompletaClick
  end
  object SaveDialog1: TSaveDialog
    Left = 175
    Top = 335
  end
  object OpenDialog1: TOpenDialog
    Filter =
      'All (*.gif;*.jpg;*.jpeg;*.bmp;*.ico;*.emf;*.wmf;*.png)|*.gif;*.j' +
      'pg;*.jpeg;*.bmp;*.ico;*.emf;*.wmf;*.png|GIF Image (*.gif)|*.gif|' +
      'JPEG Image File (*.jpg)|*.jpg|JPEG Image File (*.jpeg)|*.jpeg|Bi' +
      'tmaps (*.bmp)|*.bmp|Icons (*.ico)|*.ico|Enhanced Metafiles (*.em' +
      'f)|*.emf|Metafiles (*.wmf)|*.wmf|Portable Network Graphics (*.pn' +
      'g)|*.png'
    Title = 'Buscar Imagen'
    Left = 260
    Top = 225
  end
end

_________________
Cool
Volver arriba
Ver perfil de usuario Enviar mensaje privado Enviar email MSN Messenger
Mensaje    Asunto: Responder citando

Hola que tal César. Estoy usando parte de tu código para salvar imagenes en formato TIFF. Pero me manda error de compilacion en el cast:

Código:
 Gdiplus::Image *pGif = new Gdiplus::Image((IStream *)*streamadapter_p);


[bcc32 Error] Unit3.cpp(120): E2031 Cannot cast from 'TStreamAdapter' to 'IStream *'

Estoy con Builder C++ XE3 trial.

Gracias.
Volver arriba
Ver perfil de usuario Enviar mensaje privado MSN Messenger
Mostrar mensajes de anteriores:   
Cambiar a:  
No puedes publicar temas nuevos en este foro
No puedes responder a temas en este foro
No puedes editar tus mensajes en este foro
No puedes borrar tus mensajes en este foro
No puedes votar en las encuestas de este foro


Hosting WordPress Indedmedia desde 3,99 €
© 2002–2026 Club Builder · Funciona con phpBB.