Reputation: 41
In my project, i have to set an image rating value in any format (*.png, *.jpg, *.bmp etc.), and return the value.
I try to use
PropertyItem
. it doesnt work.
Image im = Image.FromFile("D:\\2.jpg");
int intValue = 3;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)Array.Reverse(intBytes);
byte[] result = intBytes;
PropertyItem prop = im.GetPropertyItem(18246);
prop.Value = result;
im.SetPropertyItem(prop);
Does any one do this, if yes how, thanks?
Upvotes: 3
Views: 2036
Reputation: 98
To set up Rating You have to set up two values. Rating and RatingPercent
These two values are corresponding to each other. So setting just Rating doesn't reflect Rating stars in Windows. (In fact it is very tricky because You set value, You can read it, but in Windows Explorer nothing changes).
class Program
{
static void Main(string[] args)
{
//0,1,2,3,4,5
SetRating(0);
SetRating(1);
SetRating(2);
SetRating(3);
SetRating(4);
SetRating(5);
}
private static void SetRating(short ratingValue)
{
short ratingPercentageValue = 0;
switch (ratingValue)
{
case 0: ratingPercentageValue = ratingValue; break;
case 1: ratingPercentageValue = ratingValue; break;
default: ratingPercentageValue = (short)((ratingValue - 1) * 25); break;
}
string SelectedImage = @"d:\Trash\phototemp\IMG_1200.JPG";
using (var imageTemp = System.Drawing.Image.FromFile(SelectedImage))
{
var rating = imageTemp.PropertyItems.FirstOrDefault(x => x.Id == 18246);
var ratingPercentage = imageTemp.PropertyItems.FirstOrDefault(x => x.Id == 18249);
rating.Value = BitConverter.GetBytes(ratingValue);
rating.Len= rating.Value.Length;
ratingPercentage.Value = BitConverter.GetBytes(ratingPercentageValue);
ratingPercentage.Len = ratingPercentage.Value.Length;
imageTemp.SetPropertyItem(rating);
imageTemp.SetPropertyItem(ratingPercentage);
imageTemp.Save(SelectedImage + "new" + ratingValue +".jpg");
}
}
}
Upvotes: 3
Reputation: 1763
The solution is not optimal (and hackish), but the easiest way is:
1) Use an image on your harddrive. Any image. Just rate it manually, so that the image has this property.
2) This image will work as your "dummy image", so that you can load it in order to call getPropertyItem() on it, to get the property.
3) Once you have the PropertyItem, just change its value, and use SetPropertyItem on your actual image.
string dummyFileName = @"C:\Users\<youruser>\Pictures\dummy.jpg";
string realFileName = @"C:\Users\<youruser>\Pictures\real.jpg";
string realFileNameOutput = @"C:\Users\<youruser\Pictures\real_rated.jpg";
Image dummyFile = Image.FromFile(dummyFileName);
var propertyItem = dummyFile.GetPropertyItem(18246);
Image realImage = Image.FromFile(realFileName);
realImage.SetPropertyItem(propertyItem);
realImage.Save(realFileNameOutput);
Upvotes: 0