简体   繁体   English

C#下载提取的图像

[英]c# download the extracted image

I have created a Form Application to Extracted Image , I have searched many posts , till Now I am able to download into the MemoryStream (Byte Array ). 我创建了一个Form Application来提取图像,我搜索了很多帖子,直到现在我可以下载到MemoryStream(字节数组)中。 I am not able to save that byte array into file system and check the image size .... 我无法将该字节数组保存到文件系统中并检查图像大小..

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public List<string> FetchImages(string Url)
    {
        List<string> imageList = new List<string>();


        if (!Url.StartsWith("http://") && !Url.StartsWith("https://"))
            Url = "http://" + Url;

        string responseUrl = string.Empty;
        string htmlData = ASCIIEncoding.ASCII.GetString(DownloadData(Url, out responseUrl));

        if (responseUrl != string.Empty)
            Url = responseUrl;

        if (htmlData != string.Empty)
        {
            string imageHtmlCode = "<img";
            string imageSrcCode = @"src=""";

            int index = htmlData.IndexOf(imageHtmlCode);
            while (index != -1)
            {

                htmlData = htmlData.Substring(index);


                int brackedEnd = htmlData.IndexOf('>'); //make sure data will be inside img tag
                int start = htmlData.IndexOf(imageSrcCode) + imageSrcCode.Length;
                int end = htmlData.IndexOf('"', start + 1);

                    if (end > start && start < brackedEnd)
                {
                    string loc = htmlData.Substring(start, end - start);

                        imageList.Add(loc);
                }

                    if (imageHtmlCode.Length < htmlData.Length)
                    index = htmlData.IndexOf(imageHtmlCode, imageHtmlCode.Length);
                else
                    index = -1;
            }

                for (int i = 0; i < imageList.Count; i++)
            {
                string img = imageList[i];

                string baseUrl = GetBaseURL(Url);

                if ((!img.StartsWith("http://") && !img.StartsWith("https://"))
                    && baseUrl != string.Empty)
                    img = baseUrl + "/" + img.TrimStart('/');

                imageList[i] = img;
            }
        }

        return imageList;
    }


    private byte[] DownloadData(string Url)
    {
        string empty = string.Empty;
        return DownloadData(Url, out empty);
    }

    private byte[] DownloadData(string Url, out string responseUrl)
    {
        byte[] downloadedData = new byte[0];
        try
        {
                WebRequest req = WebRequest.Create(Url);
            WebResponse response = req.GetResponse();
            Stream stream = response.GetResponseStream();

            responseUrl = response.ResponseUri.ToString();

                byte[] buffer = new byte[1024];


            MemoryStream memStream = new MemoryStream();
            while (true)
            {

                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    break;
                }
                else
                {

                    memStream.Write(buffer, 0, bytesRead);
                }
            }

                downloadedData = memStream.ToArray();

                stream.Close();
            memStream.Close();
        }
        catch (Exception)
        {
            responseUrl = string.Empty;
            return new byte[0];
        }

        return downloadedData;
    }

    private Image ImageFromURL(string Url)
    {
        byte[] imageData = DownloadData(Url);
        Image img = null;

        try
        {
            MemoryStream stream = new MemoryStream(imageData);
            img = Image.FromStream(stream);
            stream.Close();
        }
        catch (Exception)
        {
        }

        return img;
    }

    private string GetBaseURL(string Url)
    {
        int inx = Url.IndexOf("://") + "://".Length;
        int end = Url.IndexOf('/', inx);

        string baseUrl = string.Empty;
        if (end != -1)
            return Url.Substring(0, end);
        else
            return string.Empty;
    }

    private void btnGetImages_Click(object sender, EventArgs e)
    {              
        this.Cursor = Cursors.WaitCursor;

        listImages.Items.Clear();

        foreach (string image in FetchImages(txtURL.Text))
        {
            listImages.Items.Add(image);
        }

        this.Cursor = Cursors.Default;
    }

    private void btnView_Click(object sender, EventArgs e)
    {
        if (listImages.SelectedIndex != -1)
            picImage.Image = ImageFromURL(listImages.SelectedItem.ToString());
    }

    private void btnSave_Click(object sender, EventArgs e)
    {

    }

    private void btnDownload_Click(object sender, EventArgs e)
    {
        DownloadData(txtURL.Text);
    }

.. I am trying to save the memroy stream into hard drive but still not getting exact code , ..我正在尝试将内存流保存到硬盘驱动器中,但仍无法获取准确的代码,

i think this code needs some additional changes 我认为此代码需要一些其他更改

 MemoryStream memStream = new MemoryStream();
                while (true)
                {
                    //Try to read the data
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);
                    }
                }

Any Help will be appreciated 任何帮助将不胜感激

If you want to save the Byte[] array to a file, 如果要将Byte []数组保存到文件中,

Syntax : File.WriteAllBytes(string path, byte[] bytes) 语法: File.WriteAllBytes(string path, byte[] bytes)

Eg : File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO 例如: File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

refer this link for more info http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx 请参阅此链接以获取更多信息http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx

If you want to convert the Byte back to image and save to the drive. 如果要将字节转换回映像并保存到驱动器。 Eg: 例如:

byte[] bitmap = YourImage();

using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
  image.Save("image.jpg", ImageFormat.Jpeg);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM