sourcetip

이미지 URL을 system.drawing.image로 변환하려면 어떻게 해야 합니까?

fileupload 2023. 5. 23. 22:19
반응형

이미지 URL을 system.drawing.image로 변환하려면 어떻게 해야 합니까?

사용 중VB.Net예를 들어, 이미지의 URL이 있습니다.http://localhost/image.gif

시스템을 만들어야 합니다.그림그리기.해당 파일의 이미지 개체입니다.

파일을 파일에 저장한 다음 여는 것은 내 옵션 중 하나가 아니며 사용 중입니다.ItextSharp

여기 내 코드가 있습니다:

Dim rect As iTextSharp.text.Rectangle
        rect = iTextSharp.text.PageSize.LETTER
        Dim x As PDFDocument = New PDFDocument("chart", rect, 1, 1, 1, 1)

        x.UserName = objCurrentUser.FullName
        x.WritePageHeader(1)
        For i = 0 To chartObj.Count - 1
            Dim chartLink as string = "http://localhost/image.gif"
            x.writechart( ** it only accept system.darwing.image ** ) 

        Next

        x.WritePageFooter()
        x.Finish(False)

WebClient 클래스를 사용하여 이미지를 다운로드한 다음 MemoryStream을 사용하여 이미지를 읽을 수 있습니다.

C#

WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData("http://localhost/image.gif");
MemoryStream ms = new MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

VB

Dim wc As New WebClient()
Dim bytes As Byte() = wc.DownloadData("http://localhost/image.gif")
Dim ms As New MemoryStream(bytes)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(ms)

다른 답변들도 옳지만, 웹 클라이언트와 메모리 스트림이 폐기되지 않는 것을 보는 것은 마음이 아프기 때문에, 저는 당신의 코드를 다음에 넣는 것이 좋습니다.using.

코드 예제:

using (var wc = new WebClient())
{
    using (var imgStream = new MemoryStream(wc.DownloadData(imgUrl)))
    {
        using (var objImage = Image.FromStream(imgStream))
        {
            //do stuff with the image
        }
    }
}

파일 맨 위에 필요한 가져오기는 다음과 같습니다.System.IO,System.Net&System.Drawing

VB.net 에서 구문은 다음과 같습니다.using wc as WebClient = new WebClient() {기타

HttpClient를 사용하여 몇 줄의 코드로 이 작업을 비동기화할 수 있습니다.

public async Task<Bitmap> GetImageFromUrl(string url)
    {
        var httpClient = new HttpClient();
        var stream = await httpClient.GetStreamAsync(url);
        return new Bitmap(stream);
    }

iTextSharp는 URI의 다음 기능을 지원합니다.

Image.GetInstance(uri)

이를 통해 이미지를 얻을 수 있습니다.

Dim req As System.Net.WebRequest = System.Net.WebRequest.Create("[URL here]")
Dim response As System.Net.WebResponse = req.GetResponse()
Dim stream As Stream = response.GetResponseStream()

Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(stream)
stream.Close()
Dim c As New System.Net.WebClient
Dim FileName As String = "c:\StackOverflow.png"
c.DownloadFile(New System.Uri("http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=5"), FileName)
Dim img As System.Drawing.Image
img = System.Drawing.Image.FromFile(FileName)

언급URL : https://stackoverflow.com/questions/11801630/how-can-i-convert-image-url-to-system-drawing-image

반응형