Foros del Web » Programación para mayores de 30 ;) » .NET »

guardar imagenes en access

Estas en el tema de guardar imagenes en access en el foro de .NET en Foros del Web. Hola tengo un problema, tengo unas variables IzquierdaBN, FrontalBN, DerechaBN que son Bitmap y quiero guardarlas en una base de datos hecha en acces donde ...
  #1 (permalink)  
Antiguo 20/07/2005, 11:18
 
Fecha de Ingreso: abril-2005
Mensajes: 93
Antigüedad: 19 años
Puntos: 0
guardar imagenes en access

Hola tengo un problema, tengo unas variables IzquierdaBN, FrontalBN, DerechaBN que son Bitmap y quiero guardarlas en una base de datos hecha en acces donde la tabla se llama imagenes. Me podeis ayudar? Gracias!!
  #2 (permalink)  
Antiguo 20/07/2005, 15:06
Avatar de Jose_minglein2  
Fecha de Ingreso: noviembre-2004
Mensajes: 2.344
Antigüedad: 19 años, 5 meses
Puntos: 8
porque no guardas las imagenes en una carpeta y guardas en la tabla la ruta de éstas así como su nombre???
  #3 (permalink)  
Antiguo 20/07/2005, 15:08
Avatar de RootK
Moderador
 
Fecha de Ingreso: febrero-2002
Ubicación: México D.F
Mensajes: 8.004
Antigüedad: 22 años, 2 meses
Puntos: 50
Cita:
porque no guardas las imagenes en una carpeta y guardas en la tabla la ruta de éstas así como su nombre???
De hecho es la forma más ligera, sencilla, y mas común... para hacerlo
__________________
Nadie roba nada ya que en la vida todo se paga . . .

Exentrit - Soluciones SharePoint & Net
  #4 (permalink)  
Antiguo 20/07/2005, 17:00
 
Fecha de Ingreso: abril-2005
Mensajes: 93
Antigüedad: 19 años
Puntos: 0
Porque la aplicación lo que hace es transformar unas imagenes y quiero guardar en la base de datos la imagen transformada.
  #5 (permalink)  
Antiguo 20/07/2005, 23:17
Avatar de Jose_minglein2  
Fecha de Ingreso: noviembre-2004
Mensajes: 2.344
Antigüedad: 19 años, 5 meses
Puntos: 8
Si lo que haces es transformar unas imagenes, pues las puedes transformar y guardarlas en un directorio igualmente, pero bueno, si te es realmente imprescindible, y quieres que tu BD ocupe una barbaridad y funcione de forma incorrecta (con bastantes posibilidades de que se corrompa) y lenta, la solucion es poner los campos de tipo ole.
  #6 (permalink)  
Antiguo 20/07/2005, 23:28
Avatar de erick_arcini  
Fecha de Ingreso: julio-2005
Ubicación: Jaltenco / DF
Mensajes: 1.723
Antigüedad: 18 años, 9 meses
Puntos: 50
Entonces que recomiendan, bueno yo estoy haciendo un proyecto muy ambicioso y utilizo imagenes que se tienen que guardar, en este caso guardar codigos de barras y una foto que por cierto ¿de pura casualidad no tienen informacion sobre conectar una webcam a visual basic .net para poder tomar fotos?, pero volviendo al tema, que es lo mejor para una aplicacion que se va a vender, que es lo mas confiable para mi cliente guardar la imagen o poner la ruta, necesito muchas opiniones con buenos resultados, no bueno...
  #7 (permalink)  
Antiguo 21/07/2005, 00:35
Avatar de Jose_minglein2  
Fecha de Ingreso: noviembre-2004
Mensajes: 2.344
Antigüedad: 19 años, 5 meses
Puntos: 8
Según mi opinión, guardar la ruta con el nombre, ya te digo, que es lo más óptimo y rápido. Ya si lo quieres más profesional, para que el cliente no vea por ahí las imágenes, puedes, p.ej. cambiarle la extensión a los archivos y guardarlos como .dat o lo que quieras.
  #8 (permalink)  
Antiguo 21/07/2005, 03:44
 
Fecha de Ingreso: abril-2005
Mensajes: 93
Antigüedad: 19 años
Puntos: 0
Pero como se hace para guardar la ruta dentro de la base de datos. Es que tengo que tenerlo esta tarde hecho y voy de culo. Que es lo ultimo que me queda para acabar el proyecto.
  #9 (permalink)  
Antiguo 21/07/2005, 03:54
Avatar de moNTeZIon  
Fecha de Ingreso: enero-2005
Ubicación: Lliçà de Munt - BCN
Mensajes: 1.625
Antigüedad: 19 años, 3 meses
Puntos: 9
Pues tendrías que guardar las imagenes que deseas, una vez las tengas transformadas, en alguna carpeta, y una vez hecho, te guardarías la ruta y nombre del archivo en tu BD, en un campo tipo texto, y palante.

Un saludo.
__________________
..:: moNTeZIon ::..
  #10 (permalink)  
Antiguo 21/07/2005, 20:54
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
che lo chino, yo tengo la solucion que vos buscas...
  #11 (permalink)  
Antiguo 21/07/2005, 21:04
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
esta es la solucion, armate estas tres pages que te doy aca y con eso basta
para meter imagenes en acces Acces... mi ejemplo esta en www.arteca.com.ar/insert.htm

Código HTML:
<!-- insert.htm -->
<html>
	<head>
		<title>Inserts Images into Database</title>
		<style>
		body, input { font-family:verdana,arial; font-size:10pt; }
	</style>
	</head>
	<body>
		<p align="center">
			<b>Ingrese la imagen que desea enviar</b><br>
		</p>
		<table border="0" align="center">
			<tr>
				<form method="POST" enctype="multipart/form-data" action="Insert.asp">
					<td>Nombre Completo :</td>
					<td>
						<input type="text" name="fname" size="40"></td>
			</tr>
			<td>Comentario :</td>
			<td>
				<input type="text" name="lname" size="40"></td>
			</tr>
			<td>edad :</td>
			<td>
				<input type="text" name="profession" size="40">
			</td>
			</tr>
			<td>Archivo :</td>
			<td>
				<input type="file" name="file" size="40"></td>
			</tr>
			<td>
			</td>
			<td>
				<input type="submit" value="Enviar"></td>
			</tr> </form> </tr>
		</table>
	</body>
</html> 
luego insert.asp

Código HTML:
<HTML>
	<HEAD>
		<title>Inserts Images into Database</title><% ' Insert.asp %>
		<!--#include file="Loader.asp"-->
		<%
  Response.Buffer = True

  ' load object
  Dim load
    Set load = new Loader
    
    ' calling initialize method
    load.initialize
    
  ' File binary data
  Dim fileData
    fileData = load.getFileData("file")
  ' File name
  Dim fileName
    fileName = LCase(load.getFileName("file"))
  ' File path
  Dim filePath
    filePath = load.getFilePath("file")
  ' File path complete
  Dim filePathComplete
    filePathComplete = load.getFilePathComplete("file")
  ' File size
  Dim fileSize
    fileSize = load.getFileSize("file")
  ' File size translated
  Dim fileSizeTranslated
    fileSizeTranslated = load.getFileSizeTranslated("file")
  ' Content Type
  Dim contentType
    contentType = load.getContentType("file")
  ' No. of Form elements
  Dim countElements
    countElements = load.Count
  ' Value of text input field "fname"
  Dim fnameInput
    fnameInput = load.getValue("fname")
  ' Value of text input field "lname"
  Dim lnameInput
    lnameInput = load.getValue("lname")
  ' Value of text input field "profession"
  Dim profession
    profession = load.getValue("profession")  
    
  ' destroying load object
  Set load = Nothing
%>
		<style> body, input, td { font-family:verdana,arial; font-size:10pt; }
	</style>
	</HEAD>
	<body>
		<p align="center">
			<b>Estos son los datos del archivo enviado </b>
			<br>
		</p>
		<table width="700" border="1" align="center">
			<tr>
				<td>Nombre de Archivo</td>
				<td><%= fileName %></td>
			</tr>
			<tr>
				<td>URL :</td>
				<td><%= filePath %></td>
			</tr>
			<tr>
				<td>URL Completa</td>
				<td><%= filePathComplete %></td>
			</tr>
			<tr>
				<td>Tamaño
				</td>
				<td><%= fileSize %></td>
			</tr>
			<tr>
				<td>File Size Translated</td>
				<td><%= fileSizeTranslated %></td>
			</tr>
			<tr>
				<td>Tipo de archivo</td>
				<td><%= contentType %></td>
			</tr>
			<tr>
				<td>No. of Form Elements</td>
				<td><%= countElements %></td>
			</tr>
			<tr>
				<td>Nombre :</td>
				<td><%= fnameInput %></td>
			</tr>
			<tr>
				<td>Comentario :</td>
				<td><%= lnameInput %></td>
			</tr>
			<tr>
				<td>Edad :</td>
				<td><%= profession %></td>
			</tr>
		</table>
		<br>
		<br>
		<p style="PADDING-LEFT:220px">
			<%= fileName %>
			data received ...<br>
			<%
    ' Checking to make sure if file was uploaded
    If fileSize > 0 Then
    
      ' Connection string
      Dim connStr
        connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="
        connStr = connStr & Server.MapPath("FileDB.mdb")
    
      ' Recordset object
      Dim rs
        Set rs = Server.CreateObject("ADODB.Recordset")
        
        rs.Open "Files", connStr, 2, 2
        
        ' Adding data
        rs.AddNew
          rs("File Name") = fileName
          rs("FileSize") = fileSize
          rs("FileData").AppendChunk fileData
          rs("ContentType") = contentType
          rs("First Name") = fnameInput
          rs("Last Name") = lnameInput
          rs("Profession") = profession
        rs.Update
        
        rs.Close
        Set rs = Nothing
        
      Response.Write "<font color=""green"">File was successfully uploaded..."
      Response.Write "</font>"
    Else
      Response.Write "<font color=""brown"">No file was selected for uploading"
      Response.Write "...</font>"
    End If
      
      
    If Err.number <> 0 Then
      Response.Write "<br><font color=""red"">Something went wrong..."
      Response.Write "</font>"
    End If
  %>
		</p>
		<b>Si desea ingresar otra imagen, llene los datos nuevamente. Sino,<A href="webform1.aspx">
				haga click</A> aqui para salir.</b>
		<br>
		<table border="0" align="center">
			<tr>
				<form method="post" enctype="multipart/form-data" action="Insert.asp">
					<td>Nombre Completo :</td>
					<td>
						<input type="text" name="fname" size="40"></td>
			</tr>
			<TR>
				<td>Comentario :</td>
				<td>
					<input type="text" name="lname" size="40"></td>
			</TR>
			<TR>
				<td>Edad :</td>
				<td>
					<input type="text" name="profession" size="40"></td>
			</TR>
			<TR>
				<td>Archivo :</td>
				<td>
					<input type="file" name="file" size="40"></td>
			</TR>
			<TR>
				<td>
				</td>
				<td>
					<input type="submit" value="Enviar"></td>
			</TR>
			</FORM></TR>
		</table>
	</body>
</HTML> 
  #12 (permalink)  
Antiguo 21/07/2005, 21:05
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
este es el ultimo, que no me entro en el post anterior loader.asp

Código HTML:
<%
  ' -- Loader.asp --
  ' -- version 1.5
  ' -- last updated 6/13/2002

  
  Class Loader
    Private dict
    
    Private Sub Class_Initialize
      Set dict = Server.CreateObject("Scripting.Dictionary")
    End Sub
    
    Private Sub Class_Terminate
      If IsObject(intDict) Then
        intDict.RemoveAll
        Set intDict = Nothing
      End If
      If IsObject(dict) Then
        dict.RemoveAll
        Set dict = Nothing
      End If
    End Sub

    Public Property Get Count
      Count = dict.Count
    End Property

    Public Sub Initialize
      If Request.TotalBytes > 0 Then
        Dim binData
          binData = Request.BinaryRead(Request.TotalBytes)
          getData binData
      End If
    End Sub
    
    Public Function getFileData(name)
      If dict.Exists(name) Then
        getFileData = dict(name).Item("Value")
        Else
        getFileData = ""
      End If
    End Function

    Public Function getValue(name)
      Dim gv
      If dict.Exists(name) Then
        gv = CStr(dict(name).Item("Value"))
        
        gv = Left(gv,Len(gv)-2)
        getValue = gv
      Else
        getValue = ""
      End If
    End Function
    
    Public Function saveToFile(name, path)
      If dict.Exists(name) Then
        Dim temp
          temp = dict(name).Item("Value")
        Dim fso
          Set fso = Server.CreateObject("Scripting.FileSystemObject")
        Dim file
          Set file = fso.CreateTextFile(path)
            For tPoint = 1 to LenB(temp)
                file.Write Chr(AscB(MidB(temp,tPoint,1)))
            Next
            file.Close
          saveToFile = True
      Else
          saveToFile = False
      End If
    End Function
    
    Public Function getFileName(name)
      If dict.Exists(name) Then
        Dim temp, tempPos
          temp = dict(name).Item("FileName")
          tempPos = 1 + InStrRev(temp, "\")
          getFileName = Mid(temp, tempPos)
      Else
        getFileName = ""
      End If
    End Function
    
    Public Function getFilePath(name)
      If dict.Exists(name) Then
        Dim temp, tempPos
          temp = dict(name).Item("FileName")
          tempPos = InStrRev(temp, "\")
          getFilePath = Mid(temp, 1, tempPos)
      Else
        getFilePath = ""
      End If
    End Function
    
    Public Function getFilePathComplete(name)
      If dict.Exists(name) Then
        getFilePathComplete = dict(name).Item("FileName")
      Else
        getFilePathComplete = ""
      End If
    End Function

    Public Function getFileSize(name)
      If dict.Exists(name) Then
        getFileSize = LenB(dict(name).Item("Value"))
      Else
        getFileSize = 0
      End If
    End Function

    Public Function getFileSizeTranslated(name)
      If dict.Exists(name) Then
        temp = 1 + LenB(dict(name).Item("Value"))
          If Len(temp) <= 3 Then
            getFileSizeTranslated = temp & " bytes"
          ElseIf Len(temp) > 6 Then
            temp = FormatNumber(((temp / 1024) / 1024), 2)
            getFileSizeTranslated = temp & " megabytes"  
          Else
            temp = FormatNumber((temp / 1024), 2)
            getFileSizeTranslated = temp & " kilobytes"
          End If
      Else
        getFileSizeTranslated = ""
      End If
    End Function
    
    Public Function getContentType(name)
      If dict.Exists(name) Then
        getContentType = dict(name).Item("ContentType")
      Else
        getContentType = ""
      End If
    End Function

  Private Sub getData(rawData)
    Dim separator 
      separator = MidB(rawData, 1, InstrB(1, rawData, ChrB(13)) - 1)

    Dim lenSeparator
      lenSeparator = LenB(separator)

    Dim currentPos
      currentPos = 1
    Dim inStrByte
      inStrByte = 1
    Dim value, mValue
    Dim tempValue
      tempValue = ""

    While inStrByte > 0
      inStrByte = InStrB(currentPos, rawData, separator)
      mValue = inStrByte - currentPos

      If mValue > 1 Then
        value = MidB(rawData, currentPos, mValue)

        Dim begPos, endPos, midValue, nValue
        Dim intDict
          Set intDict = Server.CreateObject("Scripting.Dictionary")
    
          begPos = 1 + InStrB(1, value, ChrB(34))
          endPos = InStrB(begPos + 1, value, ChrB(34))
          nValue = endPos

        Dim nameN
          nameN = MidB(value, begPos, endPos - begPos)

        Dim nameValue, isValid
          isValid = True
          
          If InStrB(1, value, stringToByte("Content-Type")) > 1 Then

            begPos = 1 + InStrB(endPos + 1, value, ChrB(34))
            endPos = InStrB(begPos + 1, value, ChrB(34))
  
            If endPos = 0 Then
              endPos = begPos + 1
              isValid = False
            End If
            
            midValue = MidB(value, begPos, endPos - begPos)
              intDict.Add "FileName", trim(byteToString(midValue))
                
            begPos = 14 + InStrB(endPos + 1, value, stringToByte("Content-Type:"))
            endPos = InStrB(begPos, value, ChrB(13))
            
            midValue = MidB(value, begPos, endPos - begPos)
              intDict.Add "ContentType", trim(byteToString(midValue))
            
            begPos = endPos + 4
            endPos = LenB(value)
            
            nameValue = MidB(value, begPos, endPos - begPos)
          Else
            nameValue = trim(byteToString(MidB(value, nValue + 5)))
          End If

          If isValid = true Then
            intDict.Add "Value", nameValue
            intDict.Add "Name", nameN

            dict.Add byteToString(nameN), intDict
          End If
      End If

      currentPos = lenSeparator + inStrByte
    Wend
  End Sub
  
  End Class

  Private Function stringToByte(toConv)
    Dim tempChar
     For i = 1 to Len(toConv)
       tempChar = Mid(toConv, i, 1)
      stringToByte = stringToByte & chrB(AscB(tempChar))
     Next
  End Function

  Private Function byteToString(toConv)
    For i = 1 to LenB(toConv)
      byteToString = byteToString & chr(AscB(MidB(toConv,i,1))) 
    Next
  End Function
%>
y listo con esto metes los datos en una acces FileDb.mdb que tiene las columas que figuran en el recordset de insert.asp lo fundamental es el campo file data de tipo ole y el contentype de texto que son la imagen y el tipo de archivo...

mirala funcionando en www.arteca.com.ar/insert.htm
  #13 (permalink)  
Antiguo 21/07/2005, 21:10
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
cualquier cosa avisame que lo vemos.... pero yo pude meter imagenes en acces a muy buena velocidad y anda muy bien... ademas las tenes protegidas y no te ocupan el espacio del server haciendo subcarpetas ni nada , ademas aca lo bueno es que la anexas a algun usuario ... por ejemplo a alguno que este registrado o no.... podemos hacer varias cosas interesantes con imagenes en base de datos...
Cualquier cosa avisame...
  #14 (permalink)  
Antiguo 21/07/2005, 23:47
Avatar de Jose_minglein2  
Fecha de Ingreso: noviembre-2004
Mensajes: 2.344
Antigüedad: 19 años, 5 meses
Puntos: 8
Código PHP:
"no te ocupan el espacio del server " 
Y que donde guarda la información????Se la inventa access sobre la marcha???????

Código PHP:
ademas las tenes protegidas 
Estás seguro de eso????

Código PHP:
es que la anexas a algun usuario 
Y cual es la diferencia de guardar la ruta "anexandolas" a un usuario registrado o no???

Código PHP:
muy buena velocidad 
No lo dudo, cuándo ocupa actualmente tu BD????
  #15 (permalink)  
Antiguo 22/07/2005, 01:22
Avatar de moNTeZIon  
Fecha de Ingreso: enero-2005
Ubicación: Lliçà de Munt - BCN
Mensajes: 1.625
Antigüedad: 19 años, 3 meses
Puntos: 9
JAJAJA

No eres muy apologista de access eh, Jose !!

Bueno, está claro, que en velocidad no ganas nada, más bien todo lo contrario. Subir la imagen siempre hay que subirla y tardará lo que tarde. Ahora bien, no creo que tarde lo mismo en guardar y leer una imagen en la BD, que en guardar y leer un texto. Así que no hay color. Ninguna de las ventajas mencionadas son exclusivas guardando la imagen en la BD, ya que guardando la ruta tienes las mismas ventajas.

Solo reconozco una: Que llevandote la BD te lo llevas todo. OK. Pero guardando la ruta, te tienes que llevar la BD y una carpetita. Tampoco es para tanto, a cambio de un rendimiento mucho mejor de la aplicación.

También recordar que a medida que un fichero access va creciendo se va haciendo más costoso trabajar con él. Hasta el punto que se puede empezar a corromper información e ir muy, muy, muy lento el acceso ya que tiene que mover muchas Megas. Y guardar imágenes en la BD acelera mucho el crecimiento de ésta..

Saludos gente!
__________________
..:: moNTeZIon ::..
  #16 (permalink)  
Antiguo 22/07/2005, 01:39
Avatar de Jose_minglein2  
Fecha de Ingreso: noviembre-2004
Mensajes: 2.344
Antigüedad: 19 años, 5 meses
Puntos: 8
No es ninguna manía especial, pero cuando pierdes una base de datos to curra, porque dice que el archivo está corrupto, pues se te quitan las ganas de usarlo (menos mal que era personal y no profesional), y todo por meterle muchas imágenes, (cuando empezó a ocupar más de 100 MB, era problema tras problema hasta que murió).

Yo solo aconsejo, quizá fuese mi máquina que era poco potente o el S.O. pero bueno, si Access soportase mucha traya, xq sacar SQL Server?????Solo para conexiones remotas?????

Un saludo
  #17 (permalink)  
Antiguo 22/07/2005, 07:30
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
ok, mira.... yo no estoy diciendo que usar carpeta de imagenes... y referencias en una bd, no sea bueno, o que sea mejor usar bd, lo que intento es decir, que si lo que necesitas es usar imagenes en una BD o quieres hacer eso... lo que puse es una solucion, ahora si quieres hacer una carpeta con imagenes.. pues hazla, En esto de programar creo que no hay limites si te imaginas como hacer lo que quieres... Lochino pregunto como meter imagenes en un BD y yo le conteste como hacerlo... si es mejor o peor en cuanto a eficiencia lo decidira el... yo solamente le brinde una solucion... pero no me pongo a discutir para que se implemente solo lo que yo digo y nada mas.... es una manera de colaborar para que otros colaboren con migo... despues de todo cada uno hace las cosas como le gusta y le parece...
  #18 (permalink)  
Antiguo 22/07/2005, 07:37
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
El tio pregunto como hacer una cosa y Udes contestaron asi:

Eeee loque queres hacer esta maaaal

yo conteste asi:

toma amigo esto es para hacer lo que tu quieres...

creo que la pregunta no fue... que seriaa mejor para mi??? el dijo como se hace? y yo le conteste...
  #19 (permalink)  
Antiguo 22/07/2005, 07:48
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
En vez de ponerse a discutir, por que no le dan una solucion respecto de imagenes en base de datos y luego le dicen que eso a criterio de Usds, no es bueno, y le dan alguna otra opcion... Usds lo unico que aportaron son un monton de palabras, y se pusieron a criticarme ...
  #20 (permalink)  
Antiguo 22/07/2005, 09:15
Avatar de moNTeZIon  
Fecha de Ingreso: enero-2005
Ubicación: Lliçà de Munt - BCN
Mensajes: 1.625
Antigüedad: 19 años, 3 meses
Puntos: 9
Dudo que alguien haya puesto algo para atacarte a ti...

Imaginas a las conclusiones que puede llegar nuestro amigo después de leer las nuestras discusiones, y a las que llegaría con la simple respuesta a lo que él queria hacer?

No te sientas atacado hombre, que esto está para aprender y contrastar opiniones, que así aprendemos todos.

Un saludo hermano!
__________________
..:: moNTeZIon ::..
  #21 (permalink)  
Antiguo 22/07/2005, 10:39
 
Fecha de Ingreso: julio-2005
Ubicación: Córdoba
Mensajes: 254
Antigüedad: 18 años, 9 meses
Puntos: 0
Saludos ... y suerte en todo !!
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:25.