Solved

The best way to convert JPEG to BMP and save to Paradox?

Posted on 2001-09-07
7
563 Views
Last Modified: 2013-11-19
I am looking for the best and easy way for my program to open a JPEG file, convert it to BMP and save it to a paradox table with Delphi 4.

Which field in paradox is best for me, BLOB, Graphic or other? What is the simplest way to convert automatically from JPEG to BMP?


0
Comment
Question by:fhtong
7 Comments
 
LVL 27

Expert Comment

by:kretzschmar
ID: 6463758
why do you want a small jpeg image into a large bmp?
(this will waste hd-space)

sample follows
0
 
LVL 1

Expert Comment

by:mscatena
ID: 6463896
I suggest you to use a regular BLOB field.

You can use those routines tht I wrote to make the conversion.

Just to help you understand the funcion names: "para" is Portuguese to "to".

Mauro
=========================
unit JPEGUtil;
{
(c) 1998-2000 por Mauro Sant'Anna
Todos os direitos reservados
Treinamento, desenvolvimento e consultoria: M. A. S. Inform?tica LTDA
Tel: (011) 284-0466, www.mas.com.br
}
interface

uses
  Sysutils, Windows, Messages,Graphics, JPEG, Classes, Controls;

function StreamParaString(const JS: TStream): string;
procedure StringParaStream(const S: string; ST: TStream);
function ArqParaString(const Nome: string): string;
procedure StringParaArq(const S, Nome: string);
function GraphicoParaString(const I: TGraphic): string;
procedure StringParaGraphico(const Gr: string; const I: TGraphic);
function JPEGParaString(J: TJPEGImage): string;
function BMPParaString(B: TBitmap): string;
function BMPParaJPEGStr(Bmp: TBitmap): string;
function GeraTextoJPEG(const Msg, NomeFonte: string;
                 TamanhoFonte, Gap: integer;
                 CorFrente, CorFundo: TColor;
                 Estilo: TFontStyles): string;
procedure PegaBMP(Ctrl: TWinControl; B: TBitmap);
function PegaWinCtrlJPEG(Ctrl: TWinControl): string;
function PegaCtrlJPEG(Ctrl: TControl): string;

var
  JPEGPerformance: TJPEGPerformance = jpBestSpeed;
//  JPEGCompressionQuality: TJPEGQualityRange = 50;
  JPEGCompressionQuality: TJPEGQualityRange = 100;

implementation



//============ STREAM <> STRING

// Joga uma stream dentro de uma string
function StreamParaString(const JS: TStream): string;
var
  S: TStringStream;
begin
  Result := '';
  S := TStringStream.Create('');
  try
    S.CopyFrom(JS, 0);
    Result := S.DataString;
  finally
    S.Free;
  end;
end;

// Joga string dentro de uma stream
procedure StringParaStream(const S: string; ST: TStream);
var
  SS: TStringStream;
begin
  SS := TStringStream.Create(S);
  try
    ST.CopyFrom(SS, 0);
  finally
    SS.Free;
  end;
end;

//============ ARQUIVO <> STRING

// L? um arquivo inteiro dentro de uma string, dado seu nome
function ArqParaString(const Nome: string): string;
var
  SA: TFileStream;
begin
  Result := '';
  SA := TFileStream.Create(Nome, fmOpenRead);
  try
    Result := StreamParaString(SA);
  finally
    SA.Free;
  end;
end;

// Copia string para arquivo, via stream
procedure StringParaArq(const S, Nome: string);
var
  SA: TFileStream;
begin
  SA := TFileStream.Create(Nome, fmCreate);
  try
    StringParaStream(S, SA);
  finally
    SA.Free;
  end;
end;

//============ GRAPHIC <> STRING

// Joga um gr?fico (TBitmap, TJPEG) para inteiro dentro de uma string,
function GraphicoParaString(const I: TGraphic): string;
var
  S: TMemoryStream;
begin
  Result := '';
  S := TMemoryStream.Create;
  try
    I.SaveToStream(S);
    S.Seek(0, 0);
    Result := StreamParaString(S);
  finally
    S.Free;
  end;
end;

// Pega um string com gr?fico e joga para dentro de uma imagem
procedure StringParaGraphico(const Gr: string; const I: TGraphic);
var
  S: TMemoryStream;
begin
  S := TMemoryStream.Create;
  try
    StringParaStream(Gr, S);
    S.Seek(0, 0);
    I.LoadFromStream(S);
  finally
    S.Free;
  end;
end;

function JPEGParaString(J: TJPEGImage): string;
begin
  Result := GraphicoParaString(J);
end;

function BMPParaString(B: TBitmap): string;
begin
  Result := GraphicoParaString(B);
end;

// Pega uma imagem BMP, converte para JPEG e retorna como uma string
// bin?ria
function BMPParaJPEGStr(Bmp: TBitmap): string;
var
  B: TJPEGImage;
begin
  Result := '';
  B := TJPEGImage.Create;
  try
    B.Performance := JPEGPerformance;
    B.CompressionQuality := JPEGCompressionQuality;
    // Converte BMP para JPEG
    B.Assign(Bmp);
    // Retorna como string
    Result := JPEGParaString(B);
  finally
    B.Free;
  end;
end;

// Retorna um bitmap no tamanho certo e com o fundo preenchido
procedure InicializaBMP(Bmp: TBitmap; H, W, Gap: integer);
var
  R: TRect;
begin
  with Bmp do
  begin
    // Ajusta tamanho
    Height := H;
    Width  := W;
    with R do begin
      // Inicializa ret?ngulo para desenho
      R.Top := 0;
      Left := 0;
      Bottom := H;
      Right := W;
      // Desenha o fundo
      Canvas.FillRect(R);
    end;
  end;
end;

// Gera um bitmap com o texto passado. Retorna uma imagem JPEG bin?ria
// dentro da string
function GeraTextoJPEG(const Msg, NomeFonte: string;
                 TamanhoFonte, Gap: integer;
                 CorFrente, CorFundo: TColor;
                 Estilo: TFontStyles): string;
var
  Bmp: TBitmap;
begin
  Result := '';
  // Cria um bitmap para desenho
  Bmp := TBitmap.Create;
  try
    with Bmp do
    begin
      // Inicliza caracter?sticas do canvas
      Canvas.Brush.Color := CorFrente;
      Canvas.Font.Size := TamanhoFonte;
      Canvas.Font.Name := NomeFonte;
      Canvas.Font.Color := CorFundo;
      Canvas.Font.Style := Estilo;
      // Inicializa tamanho do BMP
      InicializaBMP(Bmp, Canvas.TextHeight(Msg) + Gap * 2, Canvas.TextWidth(Msg) + Gap * 2, Gap);
      // Desenha o texto
      Canvas.TextOut(Gap, Gap, Msg);
    end;
    // Retorna
    Result := BMPParaJPEGStr(Bmp);
  finally
    Bmp.Free;
  end;
end;

// Pega imagem de com componente visual e retorna como JPEG
function PegaCtrlJPEG(Ctrl: TControl): string;
var
  B: TBitmap;
begin
  // Cria um bitmap para desenho
  B := TBitmap.Create;
  try
    // Ajusta tamanho
    B.Height := Ctrl.Height - 1;
    B.Width := Ctrl.Width - 1;
    // Desenha o controle no bitmap
    Ctrl.Perform(WM_PAINT, B.Canvas.Handle, 0);
    // Converte para JPEG e retorna
    Result := BMPParaJPEGStr(B);
  finally
    B.Free;
  end;
end;

// Pega imagem de com componente visual e a coloca em um BMP
procedure PegaBMP(Ctrl: TWinControl; B: TBitmap);
var
  Cn: TCanvas;
  DC: THandle;
  R: TRect;
begin
  // Ajusta tamanho do bitmap
  B.Height := Ctrl.Height;
  B.Width := Ctrl.Width;
  // Pega Dc do controle passado
  DC := GetDC(Ctrl.Handle);
  try
    // Transforma DC em TCanvas
    Cn := TCanvas.Create;
    try
      Cn.Handle := DC;
      // Ret?ngulo de origem e destino
      R := Rect(0, 0, Ctrl.Width - 1, Ctrl.Height - 1);
      // Copia bitmap
      B.Canvas.CopyRect(R, Cn, R);
    finally
      Cn.Free;
    end;
  finally
    ReleaseDC(Ctrl.Handle, DC);
  end;
end;

function PegaWinCtrlJPEG(Ctrl: TWinControl): string;
var
  B: TBitmap;
begin
  // Cria um bitmap para desenho
  B := TBitmap.Create;
  try
    PegaBMP(Ctrl, B);
    Result := BMPParaJPEGStr(B);
  finally
    B.Free;
  end;
end;

end.
0
 
LVL 22

Expert Comment

by:mnasman
ID: 6464348
Hello

  I think you had a problems with storing the jpg pictures in the database using the DBImage, so you want to convert them to bmp.

  if you want to save the Jpg pictures in the database use image component(not dbimage) and save and restore them using, SaveToFile, LoadFromFile

  Use the BLOB field it's better than the Graphic fields, the graphic field convert the pictures to the bmp, so blob will store the pictures as binary without any modification

Best regards
Mohammed Nasman
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 27

Expert Comment

by:kretzschmar
ID: 6470331
from my paq

here is a unit which stores both grafictypes and display both in an Image-Control
tested on paradox (blobtype-binary) and Interbase (typ Blob)
the table have a structure like this

ID = Number
Typ = Char(3)
Picture=Blob

the unit

unit db_pict_u2;

interface

uses
 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
 ExtDlgs, Db, DBTables, ExtCtrls, DBCtrls, StdCtrls, Mask,
 Jpeg,  //Jpeg-Unit used
 GifUnit;  // Gif-Unit used

type
 TForm1 = class(TForm)
   Image1: TImage;              //only for Visualizing
   DBEdit1: TDBEdit;            //a other dbfield
   DBNavigator1: TDBNavigator;  //db-navigation
   Table1: TTable;              //the table, where the images are stored
   DataSource1: TDataSource;
   OpenPictureDialog1: TOpenPictureDialog;  //for loading picture
   Button1: TButton;
   procedure Button1Click(Sender: TObject); //execute load and preStore to the Blobfield
   procedure FormCreate(Sender: TObject);   //TableOpen
   procedure FormDestroy(Sender: TObject);  //TableClose
   procedure Table1AfterScroll(DataSet: TDataSet); //Retrieve Blob and Display
 private
   { Private-Deklarationen }
 public
   { Public-Deklarationen }
 end;

var
 Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);  //This i Have made easier
Var
 ExtS : String[4];  //Holds The Extension
begin
 if (Table1.State = dsEdit) or  (Table1.State = dsInsert) then    // Do only if in edit mode
 begin
   If openpicturedialog1.Execute then    // If file selected
   begin
     if Table1.FieldByName('Picture').IsBlob then   // this line can deleted
     begin  //remember the Extension
       ExtS := copy(AnsiUpperCase(ExtractFileExt(OpenPictureDialog1.FileName)),2,MaxLongInt);
       if ExtS = 'JPEG' then ExtS := 'JPG';  //Noramlize Extension
       if (ExtS = 'JPG') or (ExtS = 'GIF') then  //If one of these extensions
       begin
         try
           TBlobField(Table1.FieldByName('Picture')).LoadFromFile(openpicturedialog1.filename);  //Store
the File in the Blob
           Table1.FieldByName('Typ').AsString := ExtS; //Store the Extension in the Grafic-TypField
           image1.Picture.LoadFromFile(openpicturedialog1.filename); //Load Image, also from file
         except
           showMessage('Error during BlobOperation');
         end;
       end
       else showmessage('no jpg or gif-file selected');
     end;
   end;
 end else ShowMessage('Table is not in Edit Mode!');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 Table1.Open;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
 Table1.Close;
end;

procedure TForm1.Table1AfterScroll(DataSet: TDataSet);
Var
 MyJpegImage : TJpegImage;  //if define this gloabal, you win a little perfomance
 MyGifImage : TGifFile;           //in this case you must create and free it on a other event
 MyBlobStream : TBlobStream;
begin
 // Do Only if a Picture available
 if (Table1.FieldByName('Picture').IsBlob) and (not(Table1.FieldByName('Picture').IsNull)) then
 begin  //create a blobstream
   MyBlobStream := TBlobStream.Create(TBlobField(Table1.FieldByName('Picture')),bmRead);
   if Table1.FieldByName('Typ').Asstring = 'GIF' then  //if grafictyp = gif
   begin
     MyGifImage := TGifFile.Create;               //create GifObject, can also be done Global
     MyGifImage.LoadFromStream(MyBlobStream);     //get the information from the blob
     Image1.Picture.Assign(MyGifImage.AsBitmap);  //Display Gif
     MyGifImage.Free;                             //Free Object
   end
   else  //can only be JPG
   begin
     MyJPegImage := TJPegImage.Create;         //create JPegObject, can also be done global
     MyJPegImage.LoadFromStream(MyBlobStream); //get the information from the blob
     Image1.Picture.Assign(MyJPegImage);       //Display JPeg
     MyJPegImage.Free;                         //Free Object
   end;
   MyBlobStream.Free;  // Free Stream
 end
 else image1.Picture := Nil;  // No JPeg saved disable display
end;

end.


meikl ;-)
0
 

Accepted Solution

by:
Vanessa earned 200 total points
ID: 6495462
This incorporates the possibilities of a user selecting any 1 of 4 possible  picture extension options with the click of one button.
Remeber to include jpeg in your uses cluase!!

This sample has a dbimage and an image component on the form and a speed button and an openpicturedialog

var jp:TJpegImage;
var x,y,i:integer;
var extn:string[3];
var dummyimage:Timage;
begin
     with openpicturedialog1 do
     if execute then
     begin
          extn:='   ';
          for i:= 0 to 2 do
          extn[3-i]:=filename[length(filename)-i];
          extn:=lowercase(extn);
          if extn='jpg' then
          begin
               with table1 do  // to load into paradox
               if not (state in dsEditModes) then edit;
               jp:=TJpegImage.create;
               jp.loadFromFile(openpicturedialog1.filename);
               jp.DIBNeeded;
               dbimage1.picture.bitmap.assign(jp);
               jp.free
          end;
          if extn='bmp' then
          begin
               with table1 do
               if not (state in dsEditModes) then edit;
               dbimage1.picture.loadfromfile(filename);
          end;
          if extn='wmf' then
          begin
               with table1 do
               if not (state in dsEditmodes) then edit;
               image1.picture.loadfromfile(openpicturedialog1.filename);
               x:=image1.picture.width;
               y:=image1.picture.height;
               dummyimage:=Timage.create(self);
               dummyimage.width:=x;
               dummyimage.height:=y;
               dummyimage.canvas.draw(0,0,image1.picture.graphic);
               dbimage1.picture:=dummyimage.picture;
               dummyimage.Free
          end;
          if extn='emf' then
          begin
               with table1 do
               if not (state in dsEditmodes) then edit;
               image1.picture.loadfromfile(openpicturedialog1.filename);
               x:=image1.picture.width;
               y:=image1.picture.height;
               dummyimage:=Timage.create(self);
               dummyimage.width:=x;
               dummyimage.height:=y;
               dummyimage.canvas.draw(0,0,image1.picture.graphic);
               dbimage1.picture:=dummyimage.picture;
               dummyimage.Free
          end;
     end;
end;
0
 
LVL 6

Expert Comment

by:edey
ID: 6501304
Hi Vanessa. I am happy to see a new expert here, it's always good to see fresh faces with good ideas. OTOH, while we try to make it as easy as possible to communicate great solutions there are a few "ground rules" we, as participant, try to adhear to.  Generally it's considered bad form to propose an answer to a question unless you're absolutely sure of a couple of things:

1)Your answer should not only be correct, but should _fully_ answer the question.

2)One should be sure that the answer doesn't share too great a similarity to previous comments.

There are a couple of reasons for these _self_imposed_ guidlines, the most important being that locked question get recatagorised, so new experts don't see them easily.  Also, it's always possible that the question asker may have trouble implementing your solution, for whatever reason.  You can't see it here, because you didn't ask the question, but the asker has the option of accepting any comment as an answer, so you don't really lose anything but submitting a comment instead.

At any rate, while I'm sure that your code probably does the job well, I would think that this would be one of those times where a comment would have been more appropriate.  

GL
Mike
0
 

Author Comment

by:fhtong
ID: 6508670
I do appreciate for helps from mscatena, kretzschmar and Vanessa and I do agree with edey's comment.

My delay in accepting is due to the overloaded work for the present project. I have to test all suggestions before deciding which one fits best. Thanks to all, especially Vanessa, who gives me a simple way to solve my problem.

Experts-exchange is the best forum I have joined. Perhaps later I have to check if I can offer some of my experience to others whenever suitable.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

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…
Technology opened people to different means of presenting information, but PowerPoint remains to be above competition. Know why PPT still works today.
In this Micro Tutorial viewers will learn the basic shortcuts and functions of Illustrator. The viewer will learn about the paintbrush tool, anchor points, font sizing, and more.
Learn how to use the remote presentation tool in Prezi to allow you to harness the power of this cloud based presentation platform. You can show your presentation with a remote audience using this free tool.

757 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

19 Experts available now in Live!

Get 1:1 Help Now