Jump to content
Fivewin Brasil

Download de imagem do produto - eanpictures


Ariston Santos

Recommended Posts

Este exemplo obtém o JSON e baixa a imagem, mas o modo como faço o download está incorreto porque estou salvando o conteúdo como JPEG, mas a imagem baixada pode ter outras formatos. O que quero saber se se os senhores pode indicar um modo melhor de fazer o download.

FUNCTION PrdBaixInfo(aBars, xInfo, cFimg)
   LOCAL xmlhttp_resultado := "", _xBar := "7896806700069"
   LOCAL _xNome := "", _xNcm := "", _Cest := "", _xEmbal := "", _xQtEmb := "", _xMarca := "", _xCateg := "", _xPeso := "", _xTrib := ""

   DEFAULT cFimg := ""

   _xBar := ALLTRIM(aBars[1,2])
   IF EMPTY(_xBar)
      SysRefresh() ; MsgAlert("É preciso informar um código de barras no cadastro do produto", "Atenção!")
      return nil
   endif

   url := "http://www.eanpictures.com.br:9000/api/"+xInfo+"/"+_xBar // Ex: 7896806700069 (xInfo: desc=JSON, gtin=Imagem)

   CursorWait()

   try
		oUrl:=TUrl():New( url ) // From tip.lib
		oHttp := TipClientHttp():New( oUrl , .f. ) // From tip.lib
   catch oErr
      CursorArrow()
      SysRefresh() ; MsgAlert("Houve um erro: "+oErr:Description, "Atenção!")
      return nil
   end try

	Try
		oHttp:Open()
		_xRet := oHttp:ReadAll() // Baixa todo o conteúdo do site.
	Catch oErr
      CursorArrow()
      SysRefresh() ; MsgAlert("Houve um erro: "+oErr:Description, "Atenção!")
      return nil
	End
	oHttp:Close()
	DeleteUrlCacheEntry(url) // Lipar Cache
	
	IF EMPTY(_xRet)
      CursorArrow()
      SysRefresh() ; MsgAlert("Houve um erro na comunicação com o Webservice", "Atenção!")
      return nil
	ENDIF
	
   CursorArrow()
   
   IF '"Status":"404"' $ _xRet
      _xMsg := ""
      _xRet := "["+TiraAcentos(UnicodeToStr(_xRet, .f.))+"]"
   	hJson := {}
   	nLength := hb_JSONDecode( _xRet, @hJson )
   	for nInf := 1 to len(hJson)
   		Li := hJson[nInf]
   		if len(Li) > 0
   	      try ; _xMsg := Alltrim(Li["Status_Desc"]) ; catch ; end try && Para republicavirtual
   		endif
   	next
      SysRefresh() ; MsgInfo(_xMsg, "Info")
      return nil
   ENDIF

   IF xInfo = "desc" // Obter um JSON com as informações do proudto
      IF '"Status":"200"' $ _xRet
       * SysRefresh() ; MsgInfo(_xRet, "Ok")
         _xRet := "["+TiraAcentos(UnicodeToStr(_xRet, .f.))+"]"
      	hJson := {}
      	nLength := hb_JSONDecode( _xRet, @hJson )
      	for nInf := 1 to len(hJson)
      		Li := hJson[nInf]
      		if len(Li) > 0
      	      try ; _xNome  := LEFT(UPPER(Li["Nome"])+SPACE(50),50) ; catch ; end try && Para republicavirtual
      			try ; _xNcm   := LEFT(UPPER(Li["Ncm"])+SPACE(50),50) ; catch ; end try
      			try ; _Cest   := LEFT(UPPER(Li["Cest_Codigo"])+SPACE(02),02) ; catch ; end try
      			try ; _xEmbal := LEFT(UPPER(Li["Embalagem"])+SPACE(30),30) ; catch ; end try
      			try ; _xQtEmb := LEFT(UPPER(Li["QuantidadeEmbalagem"])+SPACE(50),50) ; catch ; end try
      			try ; _xMarca := LEFT(UPPER(Li["Marca"])+SPACE(50),50) ; catch ; end try
      			try ; _xCateg := LEFT(UPPER(Li["Categoria"])+SPACE(30),30) ; catch ; end try
      	      try ; _xPeso  := LEFT(UPPER(Li["Peso"])+SPACE(50),50) ; catch ; end try && Para republicavirtual
      	      try ; _xTrib  := LEFT(UPPER(Li["tributacao"])+SPACE(50),50) ; catch ; end try && Para republicavirtual
      		endif
      	next
         c_Txt :="DESCRIÇÃO: "+ALLTRIM(_xNome )+CRLF+;
                 "NCM......: "+ALLTRIM(_xNcm  )+CRLF+;
                 "CEST.....: "+ALLTRIM(_Cest  )+CRLF+;
                 "TIPO EMB.: "+ALLTRIM(_xEmbal)+CRLF+;
                 "QT. EMB..: "+ALLTRIM(_xQtEmb)+CRLF+;
                 "MARCA....: "+ALLTRIM(_xMarca)+CRLF+;
                 "CATEGORIA: "+ALLTRIM(_xCateg)+CRLF+;
                 "PESO.....: "+ALLTRIM(_xPeso )+CRLF+;
                 "TRUBUT...: "+ALLTRIM(_xTrib )
         IF FileWrite("eaninfo.txt", c_Txt)
            MyMsgRun("",,{||WAITRUN(GETENV("ComSpec")+" /C START NOTEPAD .\eaninfo.txt", 0 )})
         ELSE
            SysRefresh() ; MsgAlert("Não foi possível criar o arquivo .txt!", "Aviso do sistema")
         ENDIF
      else
         SysRefresh() ; MsgInfo(_xRet, "Aviso")
      endif
   ELSE // Donwload da imagem do produto
      cFimg := GetCurDir()+"\tempdir\"+_xBar+".jpg"
      FileWrite(cFimg, _xRet)
      hIni := LEFT(TIME(),8)
   	WHILE ! FILE(cFimg)
         SysWait(0.25)
         IF SECS(ELAPTIME(hIni, LEFT(TIME(),8))) > 10 ; EXIT ; ENDIF
         LOOP
   	END
      SysWait(0.25)
    * WAITRUN(GETENV("ComSpec")+" /C START NOTEPAD .\"+cFimg, 0 )
   ENDIF
RETURN NIL

 

Link to comment
Share on other sites

Ariston, como que eu faço para saber todos os códigos das imagens, para "Girar" em FOR.. NEXT por exemplo?

Se eu quiser pegar e gravar a imagem e simples assim:

// => \samples\GRABARIMG.PRG  - 15/11/2021
	#Include "FiveWin.ch"
	#define CLR_MSPURPLE RGB( 0,  120, 215 )
#define CLR_MSRED    RGB( 232,  17,  35 )
#define CLR_MSGRAY   RGB( 229, 229, 229 )
	#define TME_LEAVE    2
	STATIC oWnd, hLib
	FUNCTION Main()
	   LOCAL oBar, cTitle, cUrl, cSaveAs
   LOCAL oWnd, nRowPos, nColPos, oBtnClose, oBtnMax, oBtnMin, lDrag := .F., ;
         lRResize := .F., lBResize := .F.
	   SetBalloon( .T. )
	   SkinButtons()
	   // https://imgur.com/
   // cUrl    := "https://i.imgur.com/UQxRdAp.png"
	   // http://www.eanpictures.com.br:9000/api/gtin/78932609
   // Ariston: Se quiser somente a imagem em .PNG basta girar os codigos.
   cUrl    := "http://www.eanpictures.com.br:9000/api/gtin/78932609"  // IMAGEM
   cSaveAs := "GrabaImg.png"
	   cTitle  := "FiveWin Brasil: Grabar Imagen Desde URL"
	   // DEFINE WINDOW oWnd TITLE cTitle
   DEFINE WINDOW oWnd STYLE WS_POPUP COLOR CLR_BLACK, CLR_MSPURPLE // MDI
	   oWnd:Center()
   oWnd:Shadow()
   oWnd:bPainted = { || oWnd:Say( 8, 30, "Caption Color", CLR_RED, CLR_MSPURPLE, oWnd:oFont, .T., .T. ) }
	   oWnd:bLClicked = { | nRow, nCol | If( nRow < 25, ( oWnd:Capture(), nRowPos := nRow, nColPos := nCol, lDrag := .T. ),),;
                                     If( nRow > 25 .and. nCol > oWnd:nWidth - 25, ( oWnd:Capture(), nRowPos := nRow, nColPos := nCol, lRResize := .T. ),),;
                                     If( nRow > 25 .and. nRow > oWnd:nHeight - 25, ( oWnd:Capture(), nRowPos := nRow, nColPos := nCol, lBResize := .T. ),) }
     
   oWnd:bMMoved = { | nRow, nCol | TrackMouseEvent( oWnd:hWnd, TME_LEAVE ),;
                                   If( lDrag .and. ! IsZoomed( oWnd:hWnd ) .and. IsOverWnd( oWnd:hWnd, nRow, nCol ),;
                                       oWnd:Move( oWnd:nTop + nRow - nRowPos, oWnd:nLeft + nCol - nColPos,,, .T. ),),;
                                   If( lRResize .and. ! IsZoomed( oWnd:hWnd ) .and. IsOverWnd( oWnd:hWnd, nRow, nCol ),;    
                                       ( oWnd:SetSize( oWnd:nWidth + nCol - nColPos, oWnd:nHeight, .T. ), nColPos := nCol ),),;
                                   If( lBResize .and. ! IsZoomed( oWnd:hWnd ) .and. IsOverWnd( oWnd:hWnd, nRow, nCol ),;    
                                       ( oWnd:SetSize( oWnd:nWidth, oWnd:nHeight + nRow - nRowPos, .T. ), nRowPos := nRow ),) }  
	   oWnd:bLButtonUp = { || ReleaseCapture(), lDrag := .F., lRResize := .F., lBResize := .F. }
   oWnd:bMLeave    = { || lDrag := .F. }
	   @ 1, oWnd:nWidth - 46 BTNBMP oBtnClose BITMAP "../bitmaps/16x16/closew.bmp" ;
      FLAT NOBORDER NOROUND ACTION oWnd:End() SIZE 45, 29 ;
      COLOR CLR_BLACK, CLR_MSPURPLE
	   @ 1, oWnd:nWidth - 92 BTNBMP oBtnMax BITMAP "../bitmaps/16x16/max.bmp" ;
      FLAT NOBORDER NOROUND ACTION If( ! IsZoomed( oWnd:hWnd ), oWnd:Maximize(), oWnd:Restore() ) SIZE 45, 29 ;
      COLOR CLR_BLACK, CLR_MSPURPLE
	   @ 1, oWnd:nWidth - 138 BTNBMP oBtnMin BITMAP "../bitmaps/16x16/min.bmp" ;
      FLAT NOBORDER NOROUND ACTION If( ! IsIconic( oWnd:hWnd ), oWnd:Iconize(), oWnd:Restore() ) SIZE 45, 29 ;
      COLOR CLR_BLACK, CLR_MSPURPLE
	   oBtnClose:bMMoved = { || oBtnClose:SetColor( CLR_BLACK, If( oBtnClose:lMOver, CLR_MSRED, oWnd:nClrPane ) ) }
   oBtnMax:bMMoved   = { || oBtnMax:SetColor( CLR_BLACK, If( oBtnMax:lMOver, CLR_MSGRAY, oWnd:nClrPane ) ) }
   oBtnMin:bMMoved   = { || oBtnMin:SetColor( CLR_BLACK, If( oBtnMin:lMOver, CLR_MSGRAY, oWnd:nClrPane ) ) }
	   oWnd:bResized = { || oBtnClose:Move( 1, oWnd:nWidth - 46 ), oBtnMax:Move( 1, oWnd:nWidth - 92 ),;
                        oBtnMin:Move( 1, oWnd:nWidth - 138 ) }
	   DEFINE BUTTONBAR oBar BUTTONSIZE 60, 50 _3DLOOK TOP OF oWnd 2007
	   DEFINE BUTTON OF oBar FILENAME "..\bitmaps\16x16\floppy.bmp" FLAT         ;
      ACTION( URLDownLoad( cUrl, cSaveAs ) ) TOOLTIP "Saves this Image"
	   DEFINE BUTTON OF oBar FILENAME "..\bitmaps\16x16\Exit.bmp" FLAT           ;
      ACTION oWnd:End() TOOLTIP "Exit this app" GROUP
	   SET MESSAGE OF oWnd TO cTitle  NOINSET CLOCK DATE KEYBOARD 2007
	   // ON INIT( CLRTEST( CLR_WHITE, CLR_HRED ) )                              ;
   ACTIVATE WINDOW oWnd MAXIMIZED /*                                         ;
      ON PAINT(  DiagonalGradientFill( hDC,                                  ;
                 0, 0, oWnd:nHeight, oWnd:nWidth,                            ;
                 { { 0.16, CLR_WHITE, CLR_CYAN },                            ;
                 { 0.16, CLR_CYAN, nRGB( 181, 61, 29 ) },                    ;
                 { 0.16, nRGB( 181, 61, 29 ), nRGB( 250,157,52 ) },          ;
                 { 0.16, nRGB( 250,157,52 ), nRGB( 181, 61, 29 ) },          ;
                 { 0.16, nRGB( 181, 61, 29 ), CLR_CYAN },                    ;
                 { 0.20, CLR_CYAN, CLR_WHITE } },.T. ), PINTA( hDC ) )
                 */
	RETURN NIL
	FUNCTION URLDownLoad( cUrl, cSaveAs )
	   hLib := LOADLIBRARY( "urlmon.dll" )
	   CURSORWAIT()
	   IF FILE( cSaveAs )
	      ERASE cSaveAs
	   ENDIF
	   IF .NOT. URLDownloadToFile( 0, cUrl, cSaveAs, 0, 0 ) == 0
	      MsgInfo( "Image Not Found", "Attention!" )
	      RETURN( .F. )
	   ENDIF
	   FreeLibrary( hLib )
	   CURSORARROW()
	   ShellExecute(GetActiveWindow(),"open",'"'+cSaveAs+'"')
	RETURN( .T. )
	FUNCTION DiagonalGradientFill( hDC, nTop, nLeft, nBottom, nRight, aGradInfo, ;
                               lDirection )
	   LOCAL nClr := 1, nClrs := Len( aGradInfo )
   LOCAL nSize, nStart, nEnd
	   DEFAULT lDirection := .T.
	   IF Empty( aGradInfo )
	      RETURN NIL
	   ENDIF
	   nSize    = ( nBottom - nTop ) + ( nRight - nLeft )
   nStart   = 0
   nEnd     = 0
	   FOR nClr := 1 to nClrs
	      nStart = nEnd
      nEnd   += ( nSize * ( aGradInfo[ nClr ][ 1 ] ) )
	      DiagonalGradient( hDC, ;
                        { nTop, nLeft, nBottom, nRight },;
                          aGradInfo[ nClr ][ 2 ], ;
                          aGradInfo[ nClr ][ 3 ], ;
                          lDirection, ;
                          nStart, ;
                          nEnd )
	   NEXT
	RETURN NIL
	FUNCTION Pinta( hDC )
	   LOCAL nColor
   LOCAL nLeft   := 80
   LOCAL nRight  := 220
   LOCAL cTexto  := "FIVEWIN BRASIL THE BEST"
   LOCAL cTexto2 := "No funciona...    "
   LOCAL oFont
   LOCAL hFont
   LOCAL nLen    := LEN( cTexto )
   LOCAL cLetra, n
   LOCAL nResHoriz, nResVert
	   nResHoriz := oWnd:nHorzRes() // retorna a resolucao horizontal
   nResVert  := oWnd:nVertRes() // retorna a resolucao vertical
	   // atencao: nResolution identifica em que resolucao foram inicialmente
   // desenhadas as telas, e DEVE ter um dos seguintes valores:
   //
   // 1 =  640 X 480
   // 2 =  800 X 600
   // 3 = 1024 X 768
   // 4 = 1152 X 864
   // 5 = 1280 X 800
   // 6 = 1280 X 1024
   // 7 = 1600 X 1200
   // 8 =  768 X 1024
   // 9 = 1440 X 900
   // 10 = 1280 X 768
   // 11 = 1280 X 720
	   IF nResHoriz = 1366 .AND. nResVert = 768
	      nLeft  := 260
      nRight := 230
	   ELSEIF nResHoriz = 1360 .AND. nResVert = 768
	      nLeft  := 210
      nRight := 250
	   ELSEIF nResHoriz = 1280 .AND. nResVert = 1024
	      nLeft  := 210
      nRight := 350
	   ELSEIF nResHoriz = 1280 .AND. nResVert = 768
	      nLeft  := 170 // 210  // my computer.
      nRight := 280
	   ELSEIF nResHoriz = 1280 .AND. nResVert = 720
	      nLeft  := 200
      nRight := 200
	   ELSEIF nResHoriz = 1024 .AND. nResVert = 768
	      nLeft  :=  80
      nRight := 220
	   ELSE
	      nLeft  :=  80
      nRight := 220
	   ENDIF
	   DEFINE FONT oFont NAME "Segoe UI Symbol" SIZE 0, -80 BOLD
	   hFont := SelectObject( hDC, oFont:hFont )
	   FOR n := 1 TO nLen
	      cLetra := substr( cTexto, n, 1 )
	      nColor := SetTextColor( hDC,  CLR_GREEN )
	      // TextOut( hDC, 10, nLeft, cLetra )
      TextOut( hDC, nRight, nLeft, cLetra )
	      SetTextColor( hDC, nColor )
	      nLeft += GetTextWidth( hDC, cLetra, oFont )
	   NEXT
	   SelectObject( hDC, hFont )
	RETURN NIL
	#pragma BEGINDUMP
	#include <hbapi.h>
#include <windows.h>
	HB_FUNC( CLRTEST )
{
   int aElements[2] = { COLOR_CAPTIONTEXT, COLOR_ACTIVECAPTION };
   DWORD aColors[2];
	   aColors[ 0 ] = hb_parnl( 1 );
   aColors[ 1 ] = hb_parnl( 2 );
   SetSysColors( 2, aElements, aColors );
	}
	#pragma ENDDUMP
	DLL32 FUNCTION URLDownloadToFile( pCaller AS LONG, szURL AS STRING, szFileName ;
   AS STRING, dwReserved AS LONG, lpfnCB AS LONG ) AS LONG PASCAL              ;
   FROM "URLDownloadToFileA" LIB hlib
	// fin /end

Regards, saludos.

Link to comment
Share on other sites

  • 2 weeks later...

A ideia e bem interessante

Alguém teria um exemplo que funcione ?
Tentei com vários outros códigos aqui e nenhum deles funcionou

 

Este do exemplo do João foi o único q. consegui fazer rodar
78932609

http://www.eanpictures.com.br:9000/api/gtin/78986793 NÃO ACHA
http://www.eanpictures.com.br:9000/api/gtin/78986793 NÃO ACHA
http://www.eanpictures.com.br:9000/api/gtin/78938583 NÃO ACHA
http://www.eanpictures.com.br:9000/api/gtin/78940610 NÃO ACHA
http://www.eanpictures.com.br:9000/api/gtin/78989293 NÃO ACHA
http://www.eanpictures.com.br:9000/api/gtin/78938583 NÃO ACHA

Link to comment
Share on other sites

TiraAcentos()

FUNCTION TiraAcentos(cStr)
   LOCAL cStrNew := "", nX, aAcento, aLetras
   aAcento := {"ã","Ã","Æ","Â"," ","µ","…","·","‚","","ˆ","Ò","¡","Ö","¢","à","ä","å","“","â","£","š","á","Á","à","À","é","É","ê","Ê","í","Í","ó","Ó","õ","Õ","ô","Ô","ú","Ú","ü","Ü","ù","ç","‡","Ç","€","§","¦","º","°","ª","ƒ"}
   aLetras := {"a","A","a","A","a","A","a","A","e","E","e","E","i","I","o","O","o","O","o","O","u","U","a","A","a","A","e","E","e","E","i","I","o","O","o","O","o","O","u","U","u","U"," ","c","c","C","C",".",".",".",".",".", ""}
   FOR nX := 1 TO LEN(aAcento)
       try
       cStrNew := STRTRAN(cStr,aAcento[nX],aLetras[nX])
       cStr := cStrNew
       catch e
       end try
   NEXT
   IF EMPTY(cStrNew) ; cStrNew := cStr ; ENDIF
RETURN(cStrNew)


MyMsgRun()

// Substitua por MsgRun()

Filewrite()

FUNCTION FileWrite(cFname, cStrig)
   *----------( Alternativa ao memowrit, para salver texto em arquivo )-----------*
   LOCAL _lOk := .f., nH, _nBt, nErrNr := 0
   IF FILE(cFname)
      IF FERASE(cFname) = -1
         nErrNr := FERROR() // pegar código de erro com FERROR()
         SysRefresh() ; MsgAlert("Não foi possível excluir o arquivo "+cFname, "Erro: ("+ALLTRIM(STR(nErrNr))+") "+DosErr2Str(nErrNr))
         RETURN .F.
      ENDIF
   ENDIF
  	nH := FCreate(cFname) // Se houver erro, retorna -1
  	IF nH >= 0
   	_nBt := FWrite(nH, cStrig) // Retorna a quantidade de bytes escritos
      FClose(nH) // Retorna .T. ou .F., pegar código de erro com FERROR()
      nErrNr := FERROR()
      IF nErrNr > 0 ; _lOk := .F. ; ELSE ; _lOk := .T. ; ENDIF // Se maior que zero, houve erro. Consulte FERROR()
   ENDIF
   IF ! _lOk
      SysRefresh() ; MsgAlert("Ocorreu um erro ao criar o arquivo "+cFname, "Erro: ("+ALLTRIM(STR(nErrNr))+") "+DosErr2Str(nErrNr))
   ENDIF
RETURN _lOk

FUNCTION DosErr2Str(nErrNr)
   *-------------------( Retorna uma strig com o motivo do erro )-----------------*
   LOCAL c_Err := ""
   IF nErrNr = 02 ; c_Err := "Arquivo nao encontrado" ; ENDIF
   IF nErrNr = 03 ; c_Err := "Pasta não encontrada" ; ENDIF
   IF nErrNr = 04 ; c_Err := "Muitos arquivos abertos" ; ENDIF
   IF nErrNr = 05 ; c_Err := "Acesso negado" ; ENDIF
   IF nErrNr = 06 ; c_Err := "Handle inválido" ; ENDIF
   IF nErrNr = 08 ; c_Err := "Memória insuficiente" ; ENDIF
   IF nErrNr = 15 ; c_Err := "Especificado um drive inválido" ; ENDIF
   IF nErrNr = 19 ; c_Err := "Tentativa de gravar em disco protegido" ; ENDIF
   IF nErrNr = 21 ; c_Err := "Disco não pronto" ; ENDIF
   IF nErrNr = 23 ; c_Err := "Erro de CRC" ; ENDIF
   IF nErrNr = 29 ; c_Err := "Erro de gravação" ; ENDIF
   IF nErrNr = 30 ; c_Err := "Erro de leitura" ; ENDIF
   IF nErrNr = 32 ; c_Err := "Violação de compartilhamento" ; ENDIF
   IF nErrNr = 33 ; c_Err := "Violação de travamento" ; ENDIF
RETURN( c_Err )

 

Link to comment
Share on other sites

Esse site não sei não... tem algo errado que não está certo. Se poderia fazer facilmente assim:

	cUrl := "https://www.jesmondfruitbarn.com.au/wp-content/uploads/2016/10/Jesmond-Fruit-Barn-Oranges.jpg"
 
	XIMAGE( cUrl )
	

Regards,saludos.

Link to comment
Share on other sites

Amiguinhos.

Quando implementei esta interação em meu sistema notei que no controle acionado por REDEFINE IMAGE eu podia passar o nome do arquivo no parametro FILENAME contendo somente o nome do arquivo, não precisava da extensão, inclusive eu salvo as imagens somente com o nome ou seja o ean. Verifiquem.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...