C#: Capture multiple image and Save in same folder? - c#

Currently my code can able to do capture image and saved in defined location but if i try the same in second time image is overwrite so if same file name present in that folder, we have to change name of file dynamically.
How can I do that ?
Present screen capturing code is:
private void CaptureMyScreen()
{
try
{
//Creating a new Bitmap object
Bitmap captureBitmap = new Bitmap(1024, 768, PixelFormat.Format32bppArgb);
//Creating a Rectangle object which will capture our Current Screen
Rectangle captureRectangle = Screen.AllScreens[0].Bounds;
//Creating a New Graphics Object
Graphics captureGraphics = Graphics.FromImage(captureBitmap);
//Copying Image from The Screen
captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size);
//Saving the Image File (I am here Saving it in My D drive).
captureBitmap.Save(#"D:\Capture.jpg", ImageFormat.Jpeg);
//Displaying the Successfull Result
MessageBox.Show("Screen Captured");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

You can use GUID to get unique name for every capture file. Something like
string guid = Guid.NewGuid().ToString();
captureBitmap.Save(#"D:\Capture-" + guid + ".jpg",ImageFormat.Jpeg);
or, use current date and time for that, like this:
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
captureBitmap.Save(#"D:\Capture-" + timestamp + ".jpg",ImageFormat.Jpeg);

Related

How to Save Images In Folder After cropping using Croppie (Jquery Image cropper)

I'm Trying to save the image after cropping into folder &image path to the database using croppie but it convert to base64 & i also dont know how to send this data to controller & how can i save the image into a folder & its path to the database.
I already try to save file.write function but it was not sending back to image data to the controller
public ActionResult AddProduct(Tbl_Product product,HttpPostedFileBase file_photo)
{
string name = null;
string ext = null;
if (ModelState.IsValid==true)
{
if (file_photo != null)
{
name = Path.GetFileNameWithoutExtension(file_photo.FileName);
ext = Path.GetExtension(file_photo.FileName);
string path = Path.Combine(Server.MapPath("~/ProductImages"), name + ext);
file_photo.SaveAs(path);
}
product.ProductImage = name + ext;
product.CreatedDate = DateTime.Now;
_unitofwork.GetRepositoryInstance<Tbl_Product>().Add(product);
return RedirectToAction("Product");
}
else
{
ViewBag.CategoryList = GetCategory();
return View();
}
}
i want to save image in folder & path to database but it shows base64 image
I have written a complete post on using croppie.js with c#
A function to set croppie,
Function to crop the Image,
Then send the image date to the web method by ajax,
Convert image data to image and save it in the folder.
Here is the link,
https://shaktisinghcheema.com/image-upload-with-cropping/
Also, you may run into an issue of timeout when sending image data to web method,
Here is the link of solution to it:
Error while sending base64 string through json
I hope this might help someone who lands on this question.
In croppie, after cropping the image you will get result in base64 format, keep this base64 in some hidden field like below,
$('#imagebase64').val(base64_data);
And in you controller action method, use the following code to store image in folder.
if (product.imagebase64 != null)
{
try
{
var base64Data = Regex.Match(product.imagebase64, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
byte[] imageBytes = Convert.FromBase64String(base64Data);
string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss"); // You can write custom name here
string path = Path.Combine(Server.MapPath("~/ProductImages"), filename + ".jpg");
System.IO.File.WriteAllBytes(path, imageBytes);
}
catch (Exception ex)
{
}
}

ImageResizer - not resaving image if it's smaller than requested size

OK, I am trying to use ImageResizer component in my web app. I have following code:
var versions = new Dictionary<string, string>();
//Define the versions to generate
versions.Add("_001", "maxwidth=300&maxheight=300&format=jpg");
versions.Add("_002", "maxwidth=600&maxheight=600&format=jpg");
versions.Add("_003", "maxwidth=1920&maxheight=1080&format=jpg&process=no"); // I expect it not to resave the image if original is smaller
string uploadFolder = "...my folder path...";
if (!Directory.Exists(uploadFolder))
Directory.CreateDirectory(uploadFolder);
//Generate each version
foreach (string suffix in versions.Keys)
{
//Generate a filename (GUIDs are best).
string fileName = Path.Combine(uploadFolder, DEFAULT_IMAGE_NAME + suffix);
//Let the image builder add the correct extension based on the output file type
fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
}
file.SaveAs(uploadFolder + DEFAULT_IMAGE_NAME + "_000.jpg");
As you can tell I am saving 3 versions of one image + original image. However, I only want image to be re-encoded and re-saved if resizing is required. So if I upload 1000x1000 image I would expect that main_000.jpg and main_003.jpg are the same. However, that's not the case (ImageResizer resizes that image also, and often saved file size is bigger than main_000.jpg).
I tried adding process=no as parameter but it's not working. Anyone knows if this scenario is supported and which parameter I need to add?
//it may need to be improved
Dictionary<string, SavingSettings> SaveVersions = new Dictionary<string, SavingSettings>();
public void page_load(object sender, EventArgs e) {
//set versions:
SaveVersions.Add("xxl", new SavingSettings("xxl", new ImageResizer.ResizeSettings())); //original size
SaveVersions.Add("600px", new SavingSettings("600px", new ImageResizer.ResizeSettings(600, 600, ImageResizer.FitMode.Max, "jpg"))); //big
SaveVersions.Add("80px", new SavingSettings("80px", new ImageResizer.ResizeSettings(80, 80, ImageResizer.FitMode.Max, "jpg"))); //80 px thumb
SaveVersions.Add("260w", new SavingSettings("260w", new ImageResizer.ResizeSettings(260, 0, ImageResizer.FitMode.Max, "jpg"))); //260 px width thumb
}
public void SaveIt(string SourceFile,string TargetFileName) {
using(System.Drawing.Bitmap bmp = ImageResizer.ImageBuilder.Current.LoadImage(SourceFile, new ImageResizer.ResizeSettings())) {
foreach(System.Collections.Generic.KeyValuePair<string, SavingSettings> k in SaveVersions) {
string TargetFilePath = Server.MapPath("../img/" + k.Value.VersionName + "/" + TargetFileName + ".jpg");
string TargetFolder = Server.MapPath("../img/" + k.Value.VersionName);
if(!System.IO.Directory.Exists(TargetFolder)) System.IO.Directory.CreateDirectory(TargetFolder);
if(bmp.Width > k.Value.ResizeSetting.Width || bmp.Height > k.Value.ResizeSetting.Height) {
//you may need to resize
ImageResizer.ImageBuilder.Current.Build(bmp, TargetFilePath, k.Value.ResizeSetting, false);
} else {
//just copy it
//or in your example you can save uploaded file
System.IO.File.Copy(SourceFile, TargetFilePath);
}
}
}
}
struct SavingSettings {
public string VersionName;
public ImageResizer.ResizeSettings ResizeSetting;
public SavingSettings(string VersionName, ImageResizer.ResizeSettings ResizeSetting) {
this.VersionName = VersionName;
this.ResizeSetting = ResizeSetting;
}
}
You need to use the URL API, not the Managed API, to perform dynamic image resizing.
Just get rid of the pre-resizing code, and save the upload to disk (make sure you sanitize the filename or use a GUID instead, however).
Then, use the URL API like this:
<img src="/uploads/original.jpg?maxwidth=300&maxheight=300&format=jpg" />

Image name generation

I am working on a window phone application where I am capturing image from the primary camera and want to generate the image name based on different parameter like date ,time etc. For that I am defining a method:
private string fnGenerate()
{
string fileName = "";
// Logic to be put later.
fileName = "testImage5.jpg";
return fileName;
}
image will come from this:
public void fnSaveImage(Stream imgStream, out string imageName)
{
imageName = fnGenerateFileName();
BitmapImage appCapImg = new BitmapImage();
appCapImg.SetSource(imgStream);
IsolatedStorageFile appImgStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream appNewStream = appImgStore.CreateFile(imageName);
WriteableBitmap appWrtBmp = new WriteableBitmap(appCapImg);
appWrtBmp.SaveJpeg(appNewStream, appWrtBmp.PixelWidth, appWrtBmp.PixelHeight, 0, 10);
appNewStream.Close();
}
But as of now I have hard coded the image name, but I want to generate the image name on the above parameter. Can any one help how to generate the name for image
You search for
DateTime.Now.ToString(format);
See this link for format: http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
private string GenerateImageName()
{
var fileName = "Image_{0}{1}{2}_{3}{4}";
var date = DateTime.Now;
return String.Format(filename, date.Day, date.Month, day.Year, day.Hour, day.Minute);
}
When the DateTime object value is for example 16/1/2013 13:24, the method wil return: "Image_1312013_1324". You can change this to your preferences. Hope this helps!
You can use Guid.NewGuid() to generate your image name.
If you want your Image name to be Unique, then get the following items :
Guid
DateTime.Now
Concatenate these two and hash the overall value. An finally set the hash value as your image name. This is Security-Strong.

how to take image from physical path(local disc)

filename = Path.GetFileName(FileUpload.FileName);
HttpPostedFile pf = FileUpload.PostedFile;
System.Drawing.Image img2 = System.Drawing.Image.FromStream(pf.InputStream);
System.Drawing.Image bmp2 = img2.GetThumbnailImage(200, 210, null, IntPtr.Zero);
Imagename = objUser.UserID + filename;
Imagepath = "D:\\Shopy_Web_21-6-12\\Shopy\\Images" + Imagename;
bmp2.Save(Path.Combine(#"D:\Shopy_Web_21-6-12\Shopy\Images", Imagename));
I've converted the file upload in to two thumbnails and saved them locally, but now I need retrieve the image to display it on the user's profile. How can I get the image to display from where I've stored it?
You can create a virtual path in your application say: ..Images/ and save your images in that folder.
and after that use the below one to fetch the image URL:
string str = Server.MapPath("Images/" + Filename);
Now you will get the url to your image that can be displayed directly.
Link your images folder (...\Shopy\Images) to a virtual folder under your app so then you can link to them within <img> elements.

Image object (as a mail attachment) filepath

I am creating an add in for outlook 2007, that embeds smileys to the body of an email.
And the method i am using is as follows:
if (!string.IsNullOrEmpty(mail.HTMLBody) && mail.HTMLBody.ToLower().Contains("</body>"))
{
int mailBodyLength;
if (mail.Body == null)
{
mailBodyLength = 0;
}
else
{
mailBodyLength = mail.Body.Length;
}
//Get Image + Link
Image imagePath = image;
object linkAddress = "http://www.pentavida.cl";
//CONTENT-ID
const string SchemaPR_ATTACH_CONTENT_ID = #"http://schemas.microsoft.com/mapi/proptag/0x3712001E";
string contentID = Guid.NewGuid().ToString();
//Attach image
mail.Attachments.Add(imagePath, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, mailBodyLength, Type.Missing);
mail.Attachments[mail.Attachments.Count].PropertyAccessor.SetProperties(SchemaPR_ATTACH_CONTENT_ID, contentID);
//Create and add banner
string banner = string.Format(#"<br/><a href=""{0}"" ><img src=""cid:{1}"" ></a></body>", linkAddress, contentID);
mail.HTMLBody = mail.HTMLBody.Replace("</body>", banner);
mail.Save();
}
In this line : mail.Attachments.Add(imagePath, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, mailBodyLength, Type.Missing);
I am adding an image object (imagePath) but its throwing an exception, it worked when i put a full path of an image in the method, now i am passing through an image that was got from my resources folder. I am assuming that the method is failing because it needs a path of the image and not the Image object. How do i get the Image path name from this Image object to pass into this method?
I have an image that i got from my resources folder, i need the path of that image. How do i get that path?
Image imagePath = image;
I need the image path because i am adding the image to a new mail in outlook.
But when i pass through the Image object it throws an exception of:
Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))
But passing a string works fine.
thanks in advance.

Categories

Resources