3

ダウンロード中またはダウンロード後に画像のサイズを変更したい。これは私のコードです。品質は重要ではありません。

public void downloadPicture(string fileName, string url,string path) {
        string fullPath = string.Empty;
        fullPath = path + @"\" + fileName + ".jpg"; //imagePath
        byte[] content;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        WebResponse response = request.GetResponse();

        Stream stream = response.GetResponseStream();

        using (BinaryReader br = new BinaryReader(stream)) {
            content = br.ReadBytes(500000);
            br.Close();
        }
        response.Close();

        FileStream fs = new FileStream(fullPath, FileMode.Create); // Starting create
        BinaryWriter bw = new BinaryWriter(fs);
        try {
            bw.Write(content); // Created
        }
        finally {
            fs.Close();
            bw.Close();
        }
    }

では、どうすればそれができますか?

4

5 に答える 5

7

画像のサイズ変更は、表面上は非常に単純に見えますが、作業を開始すると多くの複雑さが伴います。自分でやらないで、まともなライブラリを使うことをお勧めします。

非常に簡単なオープンソースの無料ライブラリであるImageResizerを使用できます。

Nugetを使用してインストールするか、をダウンロードできます

nugetを使用したインストール

var settings = new ResizeSettings {
  MaxWidth = thumbnailSize,
  MaxHeight = thumbnailSize,
  Format = "jpg"
};

ImageBuilder.Current.Build(inStream, outStream, settings);
resized = outStream.ToArray();
于 2012-05-31T12:35:23.647 に答える
4

このコードをtry/finallyブロックの後に配置します-

これにより、画像のサイズが元のサイズの1/4になります。

        using (System.Drawing.Image original = System.Drawing.Image.FromFile(fullPath))
        {
            int newHeight = original.Height / 4;
            int newWidth = original.Width / 4;

            using (System.Drawing.Bitmap newPic = new System.Drawing.Bitmap(newWidth, newHeight))
            {
                using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newPic))
                {
                    gr.DrawImage(original, 0, 0, (newWidth), (newHeight));
                    string newFilename = ""; /* Put new file path here */
                    newPic.Save(newFilename, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }

もちろん、newHeight変数とnewWidth変数を変更することで、任意のサイズに変更できます。

更新:以下のコメントのように、disposeの代わりにusing(){}を使用するようにコードを変更しました。

于 2012-05-31T12:37:22.973 に答える
0

Image.FromFile(String)オブジェクトを取得するために使用できます。ImageこのサイトのImageResizingには、実際に画像のサイズを変更するための拡張メソッドがあります。

于 2012-05-31T12:41:06.730 に答える
0

私が作成したアプリケーションでは、複数のオプションを使用して関数を作成する必要がありました。かなり大きいですが、画像のサイズを変更し、アスペクト比を維持し、エッジをカットして画像の中央のみを返すことができます。

/// <summary>
    /// Resize image with an URL as source
    /// </summary>
    /// <param name="OriginalFileURL">Link to the image</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <param name="getCenter">return the center bit of the image</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromURL(String OriginalFileURL, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter)
    {
        int newheigth = heigth;
        WebResponse response = null;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(OriginalFileURL);
            response = request.GetResponse();
        }
        catch
        {
            return (System.Drawing.Image) new Bitmap(1, 1);
        }
        Stream imageStream = response.GetResponseStream();

        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromStream(imageStream);

        // Prevent using images internal thumbnail
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        if (keepAspectRatio || getCenter)
        {
            int bmpY = 0;
            double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector
            if (getCenter)
            {
                bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);// gives the Y value of the part that will be cut off, to show only the part in the center
                Rectangle section = new Rectangle(new System.Drawing.Point(0, bmpY), new System.Drawing.Size(FullsizeImage.Width, (int)(heigth * resize)));// create the section to cut of the original image
                Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);//for the correct effect convert image to bitmap.
                FullsizeImage.Dispose();//clear the original image
                using (Bitmap tempImg = new Bitmap(section.Width, section.Height))
                {
                    Graphics cutImg = Graphics.FromImage(tempImg);//              set the file to save the new image to.
                    cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);// cut the image and save it to tempImg
                    FullsizeImage = tempImg;//save the tempImg as FullsizeImage for resizing later
                    orImg.Dispose();
                    cutImg.Dispose();
                    return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero);
                }
            }
            else newheigth = (int)(FullsizeImage.Height / resize);//  set the new heigth of the current image
        }//return the image resized to the given heigth and width
        return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero);
    }

関数へのアクセスを容易にするために、いくつかのオーバーロードされた関数を追加することができます。

/// <summary>
    /// Resize image with an URL as source
    /// </summary>
    /// <param name="OriginalFileURL">Link to the image</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromURL(String OriginalFileURL, int heigth, int width)
    {
        return resizeImageFromURL(OriginalFileURL, heigth, width, false, false);
    }

    /// <summary>
    /// Resize image with an URL as source
    /// </summary>
    /// <param name="OriginalFileURL">Link to the image</param>
    /// <param name="heigth">new height</param>
    /// <param name="width">new width</param>
    /// <param name="keepAspectRatio">keep the aspect ratio</param>
    /// <returns>image with new dimentions</returns>
    public Image resizeImageFromURL(String OriginalFileURL, int heigth, int width, Boolean keepAspectRatio)
    {
        return resizeImageFromURL(OriginalFileURL, heigth, width, keepAspectRatio, false);
    }

これで、設定するオプションの最後の2つのブール値になります。次のような関数を呼び出します。

System.Drawing.Image ResizedImage = resizeImageFromURL(LinkToPicture, 800, 400, true, true);
于 2012-12-18T08:49:21.640 に答える
0

数日前に同じ質問をして、このスレッドに誘導されましたが、実際には、bitmapImageのサイズを変更したかったのです。つまり、ダウンロードしたストリームをbitmapImageに変換してからサイズを変更できます。幅または高さのいずれかを指定した場合でも、アスペクト比は維持されます。

public static async void DownloadImagesAsync(BitmapImage list, String Url)
{
   try
   {
       HttpClient httpClient = new HttpClient();
       // Limit the max buffer size for the response so we don't get overwhelmed
       httpClient.MaxResponseContentBufferSize = 256000;
       httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE           10.0; Windows NT 6.2; WOW64; Trident/6.0)");
       HttpResponseMessage response = await httpClient.GetAsync(Url);
       response.EnsureSuccessStatusCode();
       byte[] str = await response.Content.ReadAsByteArrayAsync();
       InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
       DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
       writer.WriteBytes(str);
       await writer.StoreAsync();
       BitmapImage img = new BitmapImage();
       img.SetSource(randomAccessStream);
       //img.DecodePixelHeight = 92;
       img.DecodePixelWidth = 60; //specify only width, aspect ratio maintained
       list.ImageBitmap = img;                   
   }catch(Exception e){
      System.Diagnostics.Debug.WriteLine(ex.StackTrace);
   }
}

ソースから

于 2013-05-16T10:42:33.477 に答える