Date Taken of an Image C# - c#

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

Related

Using a Resource Image as the value in RDLC Parameter

I'm trying to pass an image as a parameter to an Image in a RDLC Report. I tried using the following:
string imgPath = new Uri("pack://application:,,,/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri(AppDomain.CurrentDomain.BaseDirectory + "pack://application:,,,/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri("/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri(AppDomain.CurrentDomain.BaseDirectory + "/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri("pack://application:,,,/Resources/default_product_img.png", UriKind.Absolute).AbsoluteUri;
string imgPath = new Uri(HttpContext.Current.Server.MapPath("~/Resources/default_product_img.png")).AbsoluteUri;
string imgPath = new Uri(HostingEnvironment.MapPath("~/Resources/default_product_img.png")).AbsoluteUri;
but the display always show the red X when I run it. I managed to make this work, but the source of the image is in the same level as the .exe and not inside it.
I also tried creating a BitmapImage, but ReportParameter() only accepts strings.
Is there a way for this to work? Or should I just copy it beside the .exe file?
Things to Note:
The image source is set as External
default_product_img.png is inside Resources folder and has a Build Action of Resource
The parameter name is set as the value in Use this image:
Take the image as a bitmap and save it to a memory stream then convert the memory stream into a base64 string. Pass this string into the parameter and use that parameter as the image. In the RDLC set the image source to be database and make sure the mime type is a correct match for how you saved the bitmap to the memory stream.
string paramValue;
using (var b = new Bitmap("file path or new properties for bitmap")) {
using (var ms = new MemoryStream()) {
b.save(ms, ImageFormat.Png);
paramValue = ConvertToBase64String(ms.ToArray());
}
}
Or if you want to keep it as an external file set the image source to be external in the rdlc and pass the path to the image as file://c:\site\resources\default_product_img.png it will need to be an absolute path and you can use Server.MapPath to convert the web relative path to an absolute local path then just make sure you have file:// at the beginning of the path so the report engine knows it's a local path.

How to change the file name before store in file and database

this code is to check does the user has upload any file and the file namd.
if (FileUpload1.HasFile) {
fileName = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Data/") + fileName);
fileLocation = Server.MapPath("~/Data/") + fileName;
}
I wonder can I add the current date on the end of the file name. my file can be any type of file. I do try add on FileName= FileUpload1.FileName+updateon; but the file will save as example.jpg11062015 and the file will be corrupted.
anyone has any idea how to do it?
You can use Path to separate FileName into a file name and an extension, insert the date in the middle, and combine them back, like this:
var fn = Path.GetFileNameWithoutExtension(FileUpload1.FileName);
var ext = Path.GetExtension(FileUpload1.FileName);
var fileName = string.Format("{0}{1:yyyy-MM-dd}.{2}", fn, DateTime.Now, ext);
Try parsing the file name into parts, and inserting your date in between, like this:
var newFileName = Path.GetFileNameWithoutExtension(FileUpload1.FileName)
+ "11062015" // or wherever the date is coming from
+ Path.GetExtension(FileUpload1.FileName);
Original file name: "someFile.ext"
Modified file name: "someFile11062015.ext"

Issue in File path

In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");

How to get filepath with Uri without "file:///"

I get an image path with Uri, which is used as the source path in a report. This image is also loaded in an imagebox. The problem is that Uri adds "file:///" to the path. Therefore the image cannot be displayed on the report. How can I get the image path without that portion?
Use Uri.LocalPath:
Gets a local operating-system representation of a file name.
Just tested this in fsi:
> let u = new Uri("file:///C:/Users/Public/Test.png");;
val u : Uri = file:///C:/Users/Public/Test.png
> u.LocalPath;;
val it : string = "C:\Users\Public\Test.png"
Looks good.
If you just want to remove "file:///" from Uri try:
string uriPath =... //your path with "file:///"
string path = uriPath.Replace("file:///", "");

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.

Categories

Resources