从数据库中的url获取图像

本文关键字:获取 图像 url 数据库 | 更新日期: 2023-09-27 17:58:30

我有一个带有图像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帮助都可以。

网址如下:

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

从数据库中的url获取图像

您可以使用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

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

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

这里有一个小实用程序函数可以帮助您完成任务

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

现在,从DataTable中获取所有ImageUrl作为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))