Ridimensionare immagine, conversione in byte per scrittura in database...

venerdì 11 luglio 2014 - 06.27
Tag Elenco Tags  VB.NET  |  .NET 3.5  |  Windows XP  |  Visual Studio 2008  |  SQL Server 2008

basicdany Profilo | Expert

Ciao a tutti , ho trovato procedura che ridimensiona img:

Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(imgUpload.PostedFile.InputStream)
Dim imageHeight As Integer = imageToBeResized.Height
Dim imageWidth As Integer = imageToBeResized.Width
Dim maxHeight As Integer = 1024
Dim maxWidth As Integer = 768
imageHeight = (imageHeight * maxWidth) / imageWidth
imageWidth = maxWidth

If imageHeight > maxHeight Then
imageWidth = (imageWidth * maxHeight) / imageHeight ''
imageHeight = maxHeight
End If

Dim stream As System.IO.MemoryStream = New MemoryStream()
stream.Position = 0
Dim image As Byte() = New Byte(stream.Length) {}
stream.Read(image, 0, image.Length)

Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight)
bitmap.Save("c:\MyFile.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)


INVECE di essere salvata in un file l img devo salvarla nel db sql server in campo di tipo byte, come posso fare questo?

grazie a tutti

alx_81 Profilo | Guru

>Ciao a tutti , ho trovato procedura che ridimensiona img:
>INVECE di essere salvata in un file l img devo salvarla nel db
>sql server in campo di tipo byte, come posso fare questo?
con lo stream, puoi applicare la procedura qui di seguito:
http://www.dreamincode.net/forums/topic/103960-save-and-retrieve-images-with-sql-server/

Alla fine per sql è un binary, nulla di più..

>grazie a tutti
di nulla!
Alessandro Alpi | SQL Server MVP
MCP|MCITP|MCTS|MCT

http://blogs.dotnethell.it/suxstellino
http://suxstellino.wordpress.com
http://mvp.microsoft.com/profiles/Alessandro.Alpi

basicdany Profilo | Expert

Ciao alex, grazie, la procedura che mi indichi:

Public Function InsertImage(ByRef imgName As String, ByRef storedProc As String) As Boolean

14 Try

15 'First we need to make sure an image name was provided. If

16 'none is provided we need to show a message to the user

17 'and exit the function

18 If IsNullOrEmpty(img) Then

19 MessageBox.Show("Please provide an image to save.")

20 Exit Function

21 End If

22

23 'FileInfo instance so we can get all the

24 'information we need regarding the image

25 Dim fInfo As New FileInfo(imgName)

26

27 'Get the length of the image for the byte array

28 'we create later in the function

29 Dim len As Long = fInfo.Length

30

31 'This is the connections tring connecting to your database

32 '** NOTE: This needs to be changed to YOUR connection string **

33 Dim connString As String = "YourConnectionString"

34

35 'Open a FileStream the length of the image being inserted

36 Using stream As New FileStream(img.Trim(), FileMode.Open)

37 'Create a new byte array the size of the length of the file

38 Dim imgData() As Byte = New Byte(Convert.ToInt32(len - 1)) {}

39

40 'Read the byte array into the buffer

41 stream.Read(imgData, 0, len)

42

43 'Create our Sql connection

44 Using con As New SqlConnection(connString)

45

46 'Create the command object that will do

47 'the database work

48 Using cmd As New SqlCommand()

49 con.Open()

50

51 'Set the properties of ouor connection object

52 cmd.Connection = con

53 cmd.CommandType = CommandType.StoredProcedure

54 cmd.CommandText = storedProc

55

56 'Add the parameters for the stored procedure

57 cmd.Parameters.AddWithValue("@image_data", imgData)

58 cmd.Parameters.AddWithValue("@image_name", imgName)

59

60 'Execute the Stored Procedure

61 cmd.ExecuteNonQuery()

62

63 Return True

64 End Using

65 End Using

66 End Using

67 Catch ex As SqlException

68 MessageBox.Show(ex.ToString)

69 Return False

70 Catch ex As Exception

71 MessageBox.Show(ex.ToString)

72 Return False

73 End Try

74 End Function


Come si nota a un percorso dove prende img, nel caso mio, visto che e un applicaz web e il server non mi permette di scrivere su spazio, non devo scrivere l img su disco ma in memoria convertirla in byte e scriverla nel db!!
la mi procedura che riscrivo:

Dim imageToBeResized As System.Drawing.Image = System.Drawing.Image.FromStream(imgUpload.PostedFile.InputStream)
Dim imageHeight As Integer = imageToBeResized.Height
Dim imageWidth As Integer = imageToBeResized.Width
Dim maxHeight As Integer = 1024 '240
Dim maxWidth As Integer = 768 '320
imageHeight = (imageHeight * maxWidth) / imageWidth
imageWidth = maxWidth

If imageHeight > maxHeight Then
imageWidth = (imageWidth * maxHeight) / imageHeight ''
imageHeight = maxHeight
End If

Dim stream As System.IO.MemoryStream = New MemoryStream()
stream.Position = 0
Dim image As Byte() = New Byte(stream.Length) {}
stream.Read(image, 0, image.Length)

Dim bitmap As New Bitmap(imageToBeResized, imageWidth, imageHeight)
bitmap.Save("c:\MyFile.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)


Serve quindi evitare la scrittura su disco:

bitmap.Save("c:\MyFile.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

mi serve l'immagine in byte da poter scrivere nel db come gia faccio per altre img:

Dim conn As String = ConnectionString
connection = New SqlConnection(conn)
connection.Open()
Dim sql As String = "INSERT INTO foto(idimmobile,foto) VALUES
(@idimmobile, @foto) SELECT @@IDENTITY"
'Dim sql As String = "INSERT INTO foto(idimmobile,foto) VALUES
(@idimmobile, @foto)"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("@idimmobile", "999999")
cmd.Parameters.AddWithValue("@foto", imgByte)
Dim id As Integer = Convert.ToInt32(cmd.ExecuteScalar())


puoi aiutarmi??

grazie

totti240282 Profilo | Guru

Scusa ma qui :

Dim stream As System.IO.MemoryStream = New MemoryStream() stream.Position = 0 Dim image As Byte() = New Byte(stream.Length) {} stream.Read(image, 0, image.Length)

Non leggi nulla stream è vuoto.
C'è solo un capitano !!!!!!

basicdany Profilo | Expert

Ciao, la.procedura lo presa da internet, comunque mi restituisce l img ridimensionata!

A me servirebbe avere lo streem! per salvarlo nel db!

alx_81 Profilo | Guru

>Ciao alex, grazie, la procedura che mi indichi:
>Come si nota a un percorso dove prende img, nel caso mio, visto
>che e un applicaz web e il server non mi permette di scrivere
>su spazio, non devo scrivere l img su disco ma in memoria convertirla
>in byte e scriverla nel db!!
quel percorso viene usato per creare lo stream. Ma tu ce l'hai già.. devi usare solo la parte in cui lo stream viene inserito a database, che, come vedi, è un semplice addWithValue di un parametro.

Alessandro Alpi | SQL Server MVP
MCP|MCITP|MCTS|MCT

http://blogs.dotnethell.it/suxstellino
http://suxstellino.wordpress.com
http://mvp.microsoft.com/profiles/Alessandro.Alpi
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?

Dopo esserti registrato potrai chiedere
aiuto sul nostro Forum oppure aiutare gli altri

Consulta le Stanze disponibili.

Registrati ora !
Copyright © dotNetHell.it 2002-2025
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5