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.
Related
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)
{
}
}
I am trying to create a file path, at the end of which will be a "images" folder that the program will use with the Image command to load jpeg files.
I want the program to dynamically know to load the jpeg files from the image folder where ever the executable is launched.
I was able to find this on this site, I added the 2 bottom code lines:
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return System.IO.Path.GetDirectoryName(path);
}
}
public static string imagePath = #"\images";
public static string finalImagePath = AssemblyDirectory + imagePath;
If I set a break point, the 'finalImagePath' is:
"C:\Users\My Name\Documents\Visual Studio 2010\Projects\Universal Serial Diagnostics\bin\Debug\images"
Which is correct, but how do I incorporate that with:
Image image = Image.FromFile(#"C:\Users\My Name\Desktop\Dip\ENV500008.jpg");
Replacing the hard coded path with the dynamic path.
The ENV500008.jpg would be stored in the images folder.
Thank you.
string path = AppDomain.CurrentDomain.BaseDirectory + "ENV500008.jpg";
if (System.IO.File.Exists(path))
{
Image image = Image.FromFile(path);
// .. the rest of the code that uses the image ..
}
Image image = Image.FromFile(#finalImagePath + "\\ENV500008.jpg");
Image image5 = Image.FromFile(#finalImagePath + "\\ENV510829-2.jpg");
public static string GetAnyPath(string fileName)
{
//my path where i want my file to be created is : "C:\\Users\\{my-system-name}\\Desktop\\Me\\create-file\\CreateFile\\CreateFile\\FilesPosition\\firstjson.json"
var basePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath.Split(new string[] { "\\CreateFile" }, StringSplitOptions.None)[0];
var filePath = Path.Combine(basePath, $"CreateFile\\CreateFile\\FilesPosition\\{fileName}.json");
return filePath;
}
change .json to any type according to need
refer :https://github.com/swinalkm/create-file/tree/main/CreateFile/CreateFile
I wonder if there is any way to give a name to a writeableBitmap
I have 3 images in my folder. To display them in a gridView I convert them to a wrtieableBitmap
if (file.Count > 0)
{
var images = new List<WriteableBitmap>();
foreach (StorageFile f in file)
{
var name = f.Name;
Debug.WriteLine(f.Name);
ImageProperties properties = await f.Properties.GetImagePropertiesAsync();
if (properties.Width > 0)
{
var bitmap = new WriteableBitmap((int)properties.Width, (int)properties.Height);
Debug.WriteLine(bitmap.PixelWidth);
using (var stream = await f.OpenAsync(FileAccessMode.ReadWrite))
{
bitmap.SetSource(stream);
}
images.Add(bitmap);
Debug.WriteLine(images.Count);
}
}
The I add them to the gridView by binding the Data as in AlGridView.DataContext = images;
Now, once I interact with those images and I press a button I need to save the selection...but using an array with numbers [1,2,3]
Before converting them, as you may see above, I had a name (which is 1.png, 2.png, etc) but once they are writeablebitmaps I havenĀ“t found any way to give / get a name out of them
And
bitmap.SetVale(Name, f.Name);
Does not work, since it says it cannot convert a string into a DependencyProperty
Any ideas?
Ha!. I think I have found the solution:
properties.Title = name;
var bitmap = new WriteableBitmap((int)properties.Width, (int)properties.Height);
bitmap.SetValue(NameProperty, (string)properties.Title);
Thank you all!
I need to rename my Image (.jpg) and the new name needs to include the date taken. I can get the date taken of the image but can not include it into new File name.
Image im = new Bitmap("FileName.....");
PropertyItem pi = im.GetPropertyItem(0x132);
dateTaken = Encoding.UTF8.GetString(pi.Value);
dateTaken = dateTaken.Replace(":", "").Replace(" ", "");
string newName = dateTaken +".jpg" ;
MessageBox.Show(newName.ToString());
So is the problem that you can't get the date into the string you're trying to show in the message box or are you trying to change the filename of the image? If you want to change the image filename, you have to modify the file itself. Look at Replace part of a filename in C#
If you would like to rename your jpeg file, you could try the code below.
This code will extract the date from an image (requires the image's full file path), convert it to a different format and then use it as a new file name. The code to rename the file is commented out, so that you can see the result in the console before trying it on your local machine.
Sample Code. Please use your own fully qualified file path
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
// This is just an example directory, please use your fully qualified file path
string oldFilePath = #"C:\Users\User\Desktop\image.JPG";
// Get the path of the file, and append a trailing backslash
string directory = System.IO.Path.GetDirectoryName(oldFilePath) + #"\";
// Get the date property from the image
Bitmap image = new Bitmap(oldFilePath);
PropertyItem test = image.GetPropertyItem(0x132);
// Extract the date property as a string
System.Text.ASCIIEncoding a = new ASCIIEncoding();
string date = a.GetString(test.Value, 0, test.Len - 1);
// Create a DateTime object with our extracted date so that we can format it how we wish
System.Globalization.CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateCreated = DateTime.ParseExact(date, "yyyy:MM:d H:m:s", provider);
// Create our own file friendly format of daydayMonthMonthYearYearYearYear
string fileName = dateCreated.ToString("ddMMyyyy");
// Create the new file path
string newPath = directory + fileName + ".JPG";
// Use this method to rename the file
//System.IO.File.Move(oldFilePath, newPath);
Console.WriteLine(newPath);
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" />