Guest User

WF activity to download and save image from URL

a guest
Oct 31st, 2016
879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. // enjoy. AK :)
  2.  
  3. using System;
  4. using System.Activities;
  5. using System.Drawing;
  6. using System.Drawing.Imaging;
  7. using System.IO;
  8. using System.Net;
  9. using System.ComponentModel;
  10.  
  11. namespace WebHelpers.DownloadImageFromUrl
  12. {
  13.     public class DownloadAndSaveImage : CodeActivity
  14.     {
  15.         [RequiredArgument, Description("Full URL path to the image")]
  16.         [Category("URL")]
  17.         public InArgument<String> ImageUrl { get; set; }
  18.        
  19.         [RequiredArgument, Description("Folder to save the file in")]
  20.         [Category("Save as...")]
  21.         public InArgument<String> SaveFolderPath { get; set; }
  22.        
  23.         [RequiredArgument, Description("File name that the image will be saved as. Without extension!")]
  24.         [Category("Save as...")]
  25.         public InArgument<String> SaveFileName { get; set; }
  26.        
  27.         [RequiredArgument, Description("Image type to save as. Will determine file extension.")]
  28.         [Category("Save as...")]
  29.         public InArgument<ImageFormat> ImageFormatToUse { get; set; }
  30.        
  31.         [Category("Save as...")]
  32.         public InArgument<bool> ShouldOverwrite { get; set; }
  33.        
  34.         protected override void Execute(CodeActivityContext context)
  35.         {
  36.             string fullSavePath = Path.Combine(SaveFolderPath.Get(context), SaveFileName.Get(context)) + "." + ImageFormatToUse.Get(context).ToString().ToLower();
  37.            
  38.             if (!ShouldOverwrite.Get(context))
  39.                 if (File.Exists(fullSavePath))
  40.                     throw new IOException("File " + fullSavePath + " already exists.");
  41.            
  42.             using (WebClient webClient = new WebClient())
  43.             {
  44.                 byte[] data = webClient.DownloadData(ImageUrl.Get(context));
  45.  
  46.                 using (MemoryStream mem = new MemoryStream(data))
  47.                 {
  48.                     var downloadedImage = Image.FromStream(mem);
  49.                     downloadedImage.Save(fullSavePath, ImageFormatToUse.Get(context));
  50.                 }
  51.             }
  52.         }
  53.     }
  54. }
Add Comment
Please, Sign In to add comment