从数据库中获取URL图片

3

我有一个包含图片URL的数据库。我有一个获取这些url的存储过程(SP_GET_Image),我想执行这个存储过程,然后针对每个URL获取图片。

我想要的是本地实际的图片,而不是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的帮助。

URL长这个样子:

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


你能提供SP返回的那些DataRow的结构和示例值吗?那个URL会是完整的,像 http://ww.google.com/logo.png 吗? - Mat J
@Mathew 编辑了原始帖子。 - user3458266
1
这是您的要求吗?“您的数据库中有一些URL。您必须将它们保存在您的项目文件夹中。是这样吗?” - naveen
@naveen 我有URL,但我想将图像保存/下载到另一台服务器上,但现在我会先将它们下载到本地。因为我的图像存储在数据库中,我有一个存储过程可以获取前10个图像,我想执行该存储过程并保存每个图像(前10个)的实际图像而不是URL。 - user3458266
@user3458266,请查看我的编辑后的答案。 - ɐsɹǝʌ ǝɔıʌ
3个回答

1
你可以使用 My.Computer.Network.DownloadFile 方法来下载文件并将其存储在本地计算机或远程服务器上,如果需要,可以提供用户名和密码。由于在下载时需要指定文件名,因此你可以使用 SubString(URL.LastIndexOf("/") + 1) 方法从 URL 中提取文件名。请注意保留 HTML 标签。
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

我假设“Your_URL_Column_Name”是我存储过程返回的URL的列名? - user3458266

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\"); 

如果我想要下载到服务器上,我可以更改URL和文件路径吗? - user3458266
@user3458266,是的,您可以根据需要调整参数。在服务器上运行它,适用于Web应用程序或类似场景。 - Mat J

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方法,因为我们需要正确的图像Content-Type来获取本地文件扩展名。

现在,从DataTable中获取所有ImageUrls作为IEnumerable(Of String),并像这样调用它

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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接