从数据库中的url获取图像

时间:2014-04-16 09:30:09

标签: c# vb.net

我有一个包含图片网址的数据库。我有一个存储过程帽子GET是url的(SP_GET_Image)我想执行存储的proc然后为每个URL获取图像。

我希望本地的实际图像不是网址。

然后对于每个图像我想在本地保存它们。我有这段代码,但想知道如何在数据行中保存每个图像。

我已经开始使用代码了。

Dim CMD as new sqlCommand("StoredProcedureName")
CMD.parameters("@Parameter1", sqlDBType.Int).value = Param_1_value

Dim connection As New SqlConnection(connectionString)
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure

Dim adapter As New SqlDataAdapter(CMD)
adapter.SelectCommand.CommandTimeout = 300

'Fill the dataset'
 Dim DS as DataSet    
 adapter.Fill(ds)
 connection.Close()   

 'Now, read through your data:'
 For Each DR as DataRow in DS.Tables(0).rows
 '<-- Im not sure here how to GET EACH images locally saved.
Next

c#或vb help很好。

网址如下:

http://img.myCompany.net/p/1483/278227_20094171232290.jpg

3 个答案:

答案 0 :(得分:1)

您可以使用My.Computer.Network.DownloadFile将文件下载并存储在本地计算机或提供用户名和密码的远程服务器上(如果需要)。由于您在下载时需要指定文件名,因此可以使用SubString(URL.LastIndexOf("/") + 1)

从URL中提取文件名
For Each DR as DataRow in DS.Tables(0).Rows
       Dim URL as String = DR("Your_URL_Column_Name").ToString()
       Dim Destination as String = "\\SERVERNAME\FolderName\"
       My.Computer.Network.DownloadFile(URL, Destination & SubString(URL.LastIndexOf("/") + 1), "name", "password")
Next

答案 1 :(得分:0)

此功能可帮助您将图像列表下载到指定的本地路径

    public void DownloadFiles(IEnumerable<string> urls, string path)
    {
        if (!System.IO.Directory.Exists(path))
            System.IO.Directory.CreateDirectory(path);

        System.Threading.Tasks.Parallel.ForEach(urls, url =>
        {
            using (var downloader = new  WebClient())
            {
                var filePath = System.IO.Path.Combine(path, System.IO.Path.GetFileName(url));
                downloader.DownloadFile(url,filePath);   
            }
        });
    }

你可以使用它类似于:

var urlList= DS.Tables[0].Rows
                         .Cast<DataRow>()
                         .Select(x => x["YourColumnNameOfUrl"].ToString());
DownloadFiles(urlList,"C:\Directory\Of\Ur\Choice\"); 

答案 2 :(得分:0)

这是一个小实用程序功能,可以帮助您完成任务

Function SaveRemoteImage(remoteImageUrl As String) As Integer
    Try
        Dim request = WebRequest.Create(remoteImageUrl)
        Dim folderName = Server.MapPath("~/VB/Images/")
        Using response As WebResponse = request.GetResponse()
            Using stream As Stream = response.GetResponseStream()
                Dim imageExtension = String.Empty
                Select Case response.ContentType.ToLower
                    Case "image/bmp",
                        "image/x-bmp",
                        "image/x-ms-bmp"
                        imageExtension = ".bmp"

                    Case "image/jpeg"
                        imageExtension = ".jpeg"

                    Case "image/gif"
                        imageExtension = ".gif"

                    Case "image/png"
                        imageExtension = ".png"

                    Case Else
                        imageExtension = ".png"
                End Select
                'renaming image name as GUID to avoid conflicts
                Dim imageName = Guid.NewGuid().ToString()
                ' Download the file
                Dim destinationPath = String.Concat(
                    folderName,
                    imageName,
                    imageExtension)
                Using tempFile = File.OpenWrite(destinationPath)
                    ' Remark: if the file is very big read it in chunks
                    ' to avoid loading it into memory
                    Dim buffer = New Byte(response.ContentLength - 1) {}
                    stream.Read(buffer, 0, buffer.Length)
                    tempFile.Write(buffer, 0, buffer.Length)
                End Using
            End Using
        End Using
        Return True
    Catch ex As Exception
        Return False
    End Try
End Function

我没有使用WebClient方法,因为我们需要正确的Image Content-Type来获取本地文件扩展名。

现在,从IEnumerable(Of String)获取DataTable的所有ImageUrls并将其称为

Dim images = table.AsEnumerable().
    Select(Function(row) row.Field(Of String)("ImageUrl"))
For Each remoteImage In images
    SaveRemoteImage(remoteImage)
Next

如果你想要一些并行编程魔术,请像这样替换For Each

System.Threading.Tasks.Parallel.ForEach(images,
    Function(remoteImage) SaveRemoteImage(remoteImage))