c#下载提取的图像

时间:2016-07-23 05:36:56

标签: c# image image-extraction

我已经创建了一个表单应用程序到提取图像,我搜索了很多帖子,直到现在我能够下载到MemoryStream(字节数组)。 我无法将该字节数组保存到文件系统中并检查图像大小....

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

..我正在尝试将memroy流保存到硬盘驱动器中,但仍未获得准确的代码,

我认为此代码需要一些额外的更改

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

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

如果要将Byte []数组保存到文件中,

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

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

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

如果要将字节转换回图像并保存到驱动器。 例如:

byte[] bitmap = YourImage();

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