Grabar, recupera y mostrar imagen jpg en blob de mysql

Miguel Salas
Posts: 132
Joined: Sun Oct 23, 2005 4:09 pm
Location: Pánuco,Ver. México

Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by Miguel Salas »

Hola a Todos

Tengo un jpg que quiero grabar en campo blob de mysql , solo logré grabarlo como texto con la fmimienc() en un longtext , y tambien me falta recuperarlo y mostrarlo, he visto varios post pero no me han funcionado.
alguien que haya pasado por este problema.

saludos , desde ya gracias.
User avatar
nageswaragunupudi
Posts: 10733
Joined: Sun Nov 19, 2006 5:22 am
Location: India
Been thanked: 11 times
Contact:

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by nageswaragunupudi »

Create the field with MEDIUMBLOB type.
Size of MEDIUMBLOB is adequate normally.
Assign the value of the field with STRTOHEX( cImageBuffer )
You can read straight without any conversion.

If you use ADO and if you have recent versions of FWH, then FWH makes all this process extremely simple.

Here is an example.

Code: Select all | Expand

#include "FiveWin.Ch"#include "xbrowse.ch"#include "adodef.ch"    // IMPORTANTfunction mysqlimages()   local oCn, oRs, cSql, a   local cPath       := "c:\fwh\bitmaps\pngs\"   local cPassWord   := <yourpasswordhere>   oCn   := FW_OpenAdoConnection( { "MYSQL", "localhost", "FWH", "root", cPassWord } )   if FW_AdoTableExists( "IMAGETEST", oCn )      oCn:Execute( "DROP TABLE IMAGETEST" )   endif   FWAdoCreateTable( "IMAGETEST", ;      {  { "IMGNAME", 'C', 20, 0 }, ;         { "IMAGE",   'm', 10, 0 } }, ; // small 'm' indicates binary data      oCn )   for each a in Directory( cPath + "*.png" )      cSql  := SQL ;                          // SQL is FWH command               INSERT INTO IMAGETEST ( IMGNAME, IMAGE ) ;               VALUES ( a[ 1 ], MemoRead( cPath + a[ 1 ] ) )      oCn:Execute( cSql )   next   oRs   := FW_OpenRecordSet( oCn, "IMAGETEST" )   XBROWSER oRs TITLE "IMAGES IN MYSQL" SETUP ( ;      oBrw:nEditTypes   := EDIT_GET, ;      oBrw:lCanPaste    := .t. )   oRs:Close()   oCn:Close()return nil


Image

Advantage of using FWH functions and commands is that we can use the same code for Access, MsSql, MySql, SQLite, etc. FWH takes care of the differences in different DBMSs.

Incidentally XBrowse and TDataRow classes are excellent editors too and can handle the complexities of image data transparently.

For example, in the above example, you can copy an image from web or other sources and paste into the image cell of xbrowse with Ctrl-V and the new image is written into the MySql table automatically.
Regards

G. N. Rao.
Hyderabad, India
User avatar
rolando
Posts: 593
Joined: Sat May 12, 2007 11:47 am
Location: San Nicolás - BA - ARGENTINA

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by rolando »

Miguel,

Hice algo así (Utilizando la clase TDolphin de Daniel García Gil).

Quizás te sirva: http://softlatinoxbase.idomyweb.com/foro/viewtopic.php?f=2&t=11&sid=41e6f0aa8ac8891d997f58a938d3d2d5#p27

Rolando :D
Miguel Salas
Posts: 132
Joined: Sun Oct 23, 2005 4:09 pm
Location: Pánuco,Ver. México

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by Miguel Salas »

Agradezco a Nages y Rolando , voy a probar y les comento como me fué saludos.
Miguel Salas
Posts: 132
Joined: Sun Oct 23, 2005 4:09 pm
Location: Pánuco,Ver. México

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by Miguel Salas »

ya logré grabar en meduimblob aqui le dejo el codigo , solo que no entiendo porque no me graba 3 campos, lo hace bien con 2 ya sea el 1ro y 2do o 2do y 3ro o 1ro y 3ro solo comento las lineas de uno de ellos y no hay problema en cambio si dejo los 3 marca: Error description: Error ADODB.Recordset/3 DISP_E_MEMBERNOTFOUND: UPDATE , en la linea: oRsBoleta:update(), alguna idea del motivo, desde ya gracias

Code: Select all | Expand

      cArch := cPAth+"\tmp\temporal1.jpg"      IF file(cArch)             nHANDLE := FOpen( cArch )             nBYTES := FSEEK( nHANDLE, 0,2 )             cBUFFER := SPACE(nBYTES+1)             FSeek( nHANDLE, 0, 0 )             nBytesRead   := FRead( nHANDLE, @cBuffer, nBytes )             FClose( nHANDLE )             if nBytesRead != nBytes               SAYING := "nBytesRead = "+str(nBYTESREAD)+CHR(10)               SAYING += "nBytes     = "+str(nBYTES)+CHR(10)               SAYING += "Error Reading Data"+chr(10)               MsgInfo( saying )             else               oRsBoleta:Fields("temporal1"):AppendChunk( VTArrayWrapper():New( 17, cBUFFER ) )             endif      endif      cBuffer := ""      nBytes := nBytesRead := 0      cArch := cPAth+"\tmp\temporal2.jpg"      IF file(cArch)             nHANDLE := FOpen( cArch )             nBYTES := FSEEK( nHANDLE, 0,2 )             cBUFFER := SPACE(nBYTES+1)             FSeek( nHANDLE, 0, 0 )             nBytesRead   := FRead( nHANDLE, @cBuffer, nBytes )             FClose( nHANDLE )             if nBytesRead != nBytes               SAYING := "nBytesRead = "+str(nBYTESREAD)+CHR(10)               SAYING += "nBytes     = "+str(nBYTES)+CHR(10)               SAYING += "Error Reading Data"+chr(10)               MsgInfo( saying )             else               oRsBoleta:Fields("temporal2"):AppendChunk( VTArrayWrapper():New( 17, cBUFFER ) )             endif      endif      cBuffer := ""      nBytes := nBytesRead := 0      cArch := cPAth+"\tmp\temporal3.jpg"      IF file(cArch)             nHANDLE := FOpen( cArch )             nBYTES := FSEEK( nHANDLE, 0,2 )             cBUFFER := SPACE(nBYTES+1)             FSeek( nHANDLE, 0, 0 )             nBytesRead   := FRead( nHANDLE, @cBuffer, nBytes )             FClose( nHANDLE )             if nBytesRead != nBytes               SAYING := "nBytesRead = "+str(nBYTESREAD)+CHR(10)               SAYING += "nBytes     = "+str(nBYTES)+CHR(10)               SAYING += "Error Reading Data"+chr(10)               MsgInfo( saying )             else               oRsBoleta:Fields("temporal3"):AppendChunk( VTArrayWrapper():New( 17, cBUFFER ) )             endif      endif 
User avatar
nageswaragunupudi
Posts: 10733
Joined: Sun Nov 19, 2006 5:22 am
Location: India
Been thanked: 11 times
Contact:

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by nageswaragunupudi »

Mr Miguel Salas

The code above can be written as:

Code: Select all | Expand

oRsBoleta:Fields("temporal1"):Value := STRTOHEX( MemoRead( cPAth+"\tmp\temporal1.jpg" ) )oRsBoleta:Fields("temporal2"):Value := STRTOHEX( MemoRead( cPAth+"\tmp\temporal3.jpg" ) )
Regards

G. N. Rao.
Hyderabad, India
Miguel Salas
Posts: 132
Joined: Sun Oct 23, 2005 4:09 pm
Location: Pánuco,Ver. México

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by Miguel Salas »

ya está gracias a todos .
ahora solo falta mostrar directamente desde el campo ya que probé loadfrommemory pero no me la reconoce esta en alguna lib?

saludos
User avatar
AIDA
Posts: 879
Joined: Fri Jan 12, 2007 8:35 pm

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by AIDA »

Hola aprovechando el tema :mrgreen:

tengo un archivo PDF en un campo BLOB como se puede desplegar ese archivo en pantalla ? :roll:


Saluditos :wink:
Que es mejor que programar? creo que nada :)
Atropellada pero aqui ando :P

I love Fivewin

séʌǝɹ ןɐ ɐʇsǝ opunɯ ǝʇsǝ
User avatar
carlos vargas
Posts: 1723
Joined: Tue Oct 11, 2005 5:01 pm
Location: Nicaragua

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by carlos vargas »

"oixctrl.oixctrl.2" es un control ocx de oracle el cual es gratuito y permite mostrar hasta 500 tipos de archivos, pdf, excel, word, etc.

buca en internet sobre el

Code: Select all | Expand

PROCEDURE Concesiones_ViewDoc()   LOCAL oWnd, oOcx   LOCAL cFileName, cExtension   IF COND->( Eof() )      MsgAlert( TC( IDS_CONC_EOF_VIEWDOC ) )      RETURN   ENDIF   WaitOn( TC( IDS_VIEW_PREPAREFILE ) )   CursorWait()   cFileName  := GetFolderMyTemp() + "\" + RTrim ( COND->NOMBRE )   cExtension := Upper( cFileExt( cFileName ) )   COND->( AdsBlob2File( cFileName , "DOCUMENTO" ) )   WaitOff()   CursorArrow()   //IF !Empty( cExtension ) .and. cExtension $ "PDF_XLS_DOC_XLSX_DOCX_PPT_PPTX_JPG_PNG_BMP"   //   ShellExecute( oDlgE:hWnd, "open", cFileName )   //ELSE      IF !IsActiveX( "oixctrl.oixctrl.2" )         MsgStop( TC( IDS_VIEW_NOINSTALLOCX ) )         RETURN      ENDIF      DEFINE WINDOW oWnd TITLE TC( IDS_VIEW_TITLE ) ICON GetIcon()      DEFINE BUTTONBAR OF oWnd 3D SIZE 60, 60 2010      DEFINE BUTTON NAME "TB_SALIR" OF oWnd:oBar ACTION oWnd:END() PROMPT TC( IDS_VIEW_TB1 )      oOcx := TActiveX():New( oWnd, "oixctrl.oixctrl.2" )      oWnd:oClient := oOcx      oWnd:SetSize( 800, 600 )      oOcx:ViewFile( FALSE, cFileName )      ACTIVATE WINDOW oWnd ON INIT oWnd:MAXIMIZE() VALID ( oOcx:Close(), oOcx := NIL, FileDelete( cFileName ), TRUE )   //ENDIFRETURN
Salu2
Carlos Vargas
Desde Managua, Nicaragua (CA)
User avatar
AIDA
Posts: 879
Joined: Fri Jan 12, 2007 8:35 pm

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by AIDA »

Hola estoy tratando de meter archivos PDF en un campo BLOB pero cuando llega al registro 30 se truena el programita :shock: y me sale esto. :cry:

Image

este es el código que hice me pueden ayudar tengo que meter 20000 archivos PDF

Code: Select all | Expand

Function cargapdf()local cFile, xuData, xxxx:=0 oQry := TDolphinQry():New( "SELECT * FROM polizario order by archivo" )  oQry:GOTOP() DO WHILE !oQry:EOF()cFile := oQry:archivoxuData = D_ReadFile( cFile )oServer:Insert( "pdf", { "archivo", "documento" }, { GetOnlyName2( cFile ), xuData } ) xx:=xx+1                    oQry:skip()         loop                   oQry:skip()        ENDDO Return FUNCTION GetOnlyName2( cFile )   LOCAL nRat   IF ! Empty( cFile )      nRat = RAt( "\", cFile )      cFile = SubStr( cFile, nRat + 1 )   ENDIFRETURN cFile


Muchas gracias espero me puedan ayudar

Saluditos :wink:
Que es mejor que programar? creo que nada :)
Atropellada pero aqui ando :P

I love Fivewin

séʌǝɹ ןɐ ɐʇsǝ opunɯ ǝʇsǝ
User avatar
carlos vargas
Posts: 1723
Joined: Tue Oct 11, 2005 5:01 pm
Location: Nicaragua

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by carlos vargas »

Code: Select all | Expand

#ifndef __XHARBOUR__#include "hbcompat.ch"#endif FUNCTION CargaPDF()    LOCAL cFile, xuData    oQry := TDolphinQry():New( "SELECT * FROM polizario order by archivo" )    oQry:GOTOP()        DO WHILE !oQry:EOF()        cFile  := oQry:archivo        xuData := FileStr( cFile )        oServer:Insert( "pdf", { "archivo", "documento" }, { cFileName( cFile ), HB_Base64Encode( xuData, len( xuData ) ) } )        xuData := NIL        oQry:skip()        IF mod( oQry:Recno(), 10 )==0 //aca modificar el 10 segun tamaño de archivos, la idea es que cada 2 segundos se realize el sysrefresh             SysRefresh()        ENDIF    ENDDO        oQry:end()    RETURN 


la idea es que el campo "documento" sea de tipo TEXT, el archivo binario PDF es leido por filestr (pertenece a ct.lib), pasado a un a variable, y luego codificado de binario a un tipo que solo se usen texto. sirve tambien HB_StrToHex, pero este duplica el tamaño del archivo, dado que cada byte es convertido a hexadecimal, en este caso HB_Base64Encode es mas eficiente ya que crea una cadena de 1.3 en relacion al tamaño original, lo cual ahorra en tamaño la cadena/archivo codificada.

en otras palabras puedes usar las funciones hb_StrToHex, hb_HexToStr, en lugar de las Base64, es opcional.

para decodificar se usa la funcion

HB_Base64Decode( <cBase64> ) --> cString
esta es la info de la otra funcion
HB_Base64Encode( <cString>, <nBytes> ) --> cBase64

Code: Select all | Expand

cFile := HB_Base64Decode( oQry:documento )StrFile( cFile, oQry:archivo ) 


salu2
carlos vargas
Salu2
Carlos Vargas
Desde Managua, Nicaragua (CA)
User avatar
AIDA
Posts: 879
Joined: Fri Jan 12, 2007 8:35 pm

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by AIDA »

Muchas gracias por tu ayuda y por la información :mrgreen:

la aplicare y te comento como me fue :)


Gracias :D



Saluditos :wink:
Que es mejor que programar? creo que nada :)
Atropellada pero aqui ando :P

I love Fivewin

séʌǝɹ ןɐ ɐʇsǝ opunɯ ǝʇsǝ
User avatar
AIDA
Posts: 879
Joined: Fri Jan 12, 2007 8:35 pm

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by AIDA »

Ya compile y me salieron los siguientes errores :shock:


Error: Unresolved external '_HB_FUN_HB_BASE64ENCODE' referenced from C:\FWH\PEGASOMYSQL\OBJ\TEST.OBJ

y con este igual


Error: Unresolved external '_HB_FUN_HB_STRTOHEX' referenced from C:\FWH\PEGASOMYSQL\OBJ\TEST.OBJ


no se que libreria me falta ?


Saluditos :wink:
Que es mejor que programar? creo que nada :)
Atropellada pero aqui ando :P

I love Fivewin

séʌǝɹ ןɐ ɐʇsǝ opunɯ ǝʇsǝ
User avatar
cnavarro
Posts: 6572
Joined: Wed Feb 15, 2012 8:25 pm
Location: España
Has thanked: 4 times
Been thanked: 6 times

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by cnavarro »

Creo que con este comando sabras en que libreria esta cualquier funcion

C:\Harbour\harb20131007\bin>hbmk2 -find HB_STRTOHEX
Harbour core (installed):
hb_StrToHex()

C:\Harbour\harb20131007\bin>hbmk2 -find HB_BASE64ENCODE
Harbour core (installed):
hb_base64Encode()
Cristobal Navarro
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
User avatar
AIDA
Posts: 879
Joined: Fri Jan 12, 2007 8:35 pm

Re: Grabar, recupera y mostrar imagen jpg en blob de mysql

Post by AIDA »

ya quedo funcionando con esta lib http://www.salc.com.br/atual/tip.rar

la lib tiene los comandos que faltaban

HB_Base64Decode( <cBase64> ) --> cString
esta es la info de la otra funcion
HB_Base64Encode( <cString>, <nBytes> ) --> cBase64


y con esto ampliado

Code: Select all | Expand

//-------------------------------------------------------------------------------//     static function conectar()      local xFile, xuData     LOCAL oErr, lRet := .f.   LOCAL hIni      := HB_ReadIni( "conecxion.ini" ) // PARA LEER ARCHIVOS .ini   *LOCAL oServer   := NIL   LOCAL cServer   := hIni["mysql"]["host"] ,;      // NOMBRE DEL HOST (localhost)         cUser     := hIni["mysql"]["user"] ,;      // NOMBRE DEL USUARIO (root)         cPassword := hIni["mysql"]["psw"] ,;       // CLAVE DEL USUARIO  (vacio por ahora)         nPort     := val(hIni["mysql"]["port"]) ,; // PUERTO DE CONEXION (3306)         cDBName   := hIni["mysql"]["dbname"] ,;    // NOMBRE DE LA BASE DE DATOS (sisprocom)         nFlags    := val(hIni["mysql"]["flags"])   // NUMERO DE FLAG (0)         TRY    oServer = TDolphinSrv():New( cServer, cUser, cPassword, nPort, nFlags, cDBName )    * ?oServer    CATCH oErr      MSGALERT( "ERROR FATAL: No hubo Conexión con el SERVIDOR" + CRLF + CRLF + ;                oErr:Description(), " SISPROCOM - MYSQL" )                           oServer:Execute("set session wait_timeout=86400")     // 28880   IF oServer:lError      MsgStop('Error al intentar establecer wait_timeout','Error')      oServer:end()      return .f.   ENDIF  oServer:Execute("set session interactive_timeout=28880")   if oServer:lError      MsgStop('Error al intentar establecer interactive_timeout','Error')      oServer:end()      return .f.   ENDIF   oServer:Execute("set session sql_big_selects=1")   if oServer:lError      MsgStop('Error al intentar establecer sql_big_selects=1','Error')      oServer:end()      return .f.   ENDIF   oServer:Execute("set @lower_case_table_names=1")   if oServer:lError     MsgStop('Error al intentar establecer set @lower_case_table_names=1','Error')      oServer:end()      return .f.   ENDIF   oServer:Execute("SET lc_time_names = 'es_ES'")   if oServer:lError   MsgStop("Error al intentar establecer SET lc_time_names = 'es_ES'",'Error')      oServer:end()      return .f.   ENDIF         oServer:Execute("set session max_allowed_packet=16G")   if oServer:lError      MsgStop('Error al intentar establecermax_allowed_packet=16M','Error')      oServer:end()      return .f.   ENDIF                  RETURN( lRet ) 
Que es mejor que programar? creo que nada :)
Atropellada pero aqui ando :P

I love Fivewin

séʌǝɹ ןɐ ɐʇsǝ opunɯ ǝʇsǝ
Post Reply