Image to Byte[] harder than thought 2 challenges - arrays

This is my 5th post over a month trying to solve what I thought was a simple problem: Write and read a small bitmap to a class.
My class:
public class Task
public byte? TaskImage { get; set; }
I recreate the bitmap in the controller after an edit, the bitmap is contained in System.Drawing. This line writes to a folder as a test. It works.
mybmp.Save("C:\\temp\\lot1.bmp",System.Drawing.Imaging.ImageFormat.Gif);
I think this puts it in a memory stream as a .bmp: Should this be .gif??
MemoryStream ms = new MemoryStream();
mybmp.Save(ms, System.Drawing.Imaging.ImageFormat.bmp);
CHALLENGE 1 provide inline code to convert to byte[] and write to class.
Task.TaskImage =
db.SaveChanges();
Later I pass the data via a viewmodel to my view and use the ForEach item concept to display the image.
CHALLENGE 2 code to display in view table:
<img src="data:image/gif;base64,#Convert.ToBase64String(item.TaskImage.Value)" />
This code has been provided by a contributor but causes this error.
Error 2 Argument 1: cannot convert from 'method group' to 'byte[]'
It was suggested I ask a new question.
I'm a beginner so please be explicit. When I have a working answer I'll go back and post answers to my earlier posts to help others.

I am assuming, you are properly saving the byte array and you already have contents of your image as a byte[]
why don't you try this, if you are using MVC4
<img src="#Url.Action("GetImage", "Controller", new{id=#Model.Id})"
alt = "img" />
where GetImage is :
public ActionResult GetImage(int id)
{
var imageByteArray= GetImageByte(id)
return File(imageByteArray, "Image/jpg");
}

Got it!
Challenge 1 the write bitmap into a byte[] field:
mybmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] byteArray = new byte[0];
ms.Close();
var lottoupdate = db.Lots //each task row contains the lotid to which
.Where(i => i.LotID == lotID) //it is associated. Find the LotID then
.Single(); // update the taskimage field in the lot class
byteArray = ms.ToArray();
lottoupdate.TaskImage = byteArray;
db.Entry(lottoupdate).State = EntityState.Modified;
db.SaveChanges();
There was a error in the lottoupdate.TaskImage=byteArray; line because TaskImage was nullable.
public class Task
public byte? TaskImage { get; set; }
So I removed the? therefore requiring data. I now seed the field.
Challenge 2 With the TaskImage byte[] passed in the viewmodel, display the image in the view table:
<text> #{
string imageBase64 = Convert.ToBase64String(#item.TaskImage);
String imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
}
</text>
<td><img src="#imageSrc" alt="Lot chart" border="0" /></td>
This displays the image in a table row. I needed the 'text' tags because html5 did not like the razor code without it. Note that I am not testing for null data, probably should. My program seeds an "base" image into the db.
I hope this helps someone else, it took about 30 hours of looking for this beginner.

Related

ClassCastException - java.lang.String cannot be cast to com.codename1.ui.Image

I am consuming a JSON string that contains an image object among other objects. From this I create a PropertyBusinessObject which has a the following
public final Property<EncodedImage, Profile> profilePic = new Property<>("profilePic", EncodedImage.class);
I have created a method in the PropertyBusinessObject
public EncodedImage getProfilePic() {
return profilePic.get();
}
I populate my data into the Property business object as follows:
profile.getPropertyIndex().populateFromMap((Map) profileObject);
When I try to display the image on the form using the following code,
ScaleImageLabel profilePic = new ScaleImageLabel(profile.getProfilePic()) {
#Override
protected Dimension calcPreferredSize() {
Dimension dimension = super.calcPreferredSize();
dimension.setHeight(Math.min(dimension.getHeight(), Display.getInstance().convertToPixels(40)));
return dimension;
}
};
profilePic.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
container.add(BorderLayout.NORTH, profilePic);
I get a ClassCastException
Exception: java.lang.ClassCastException - java.lang.String cannot be cast to com.codename1.ui.Image
Can anyone help me resolve, or suggest another way of consuming the JSON string?
populateFromMap doesn't currently support Base64 images, I'll add that as an option as that use case makes sense. Should be there with the Friday update.

Convert A Byte[] Array to Image in Xamarin Forms

Before asking this question I googled a lot but couldn't find a solution that suits mine.
In Xamarin.Forms I have a byte[] array and I want to Convert that byte[] array to an Image. How can I achieve that, this is what I tried:
In Front End(XAML):
<StackLayout BackgroundColor="Olive" x:Name="imagePanel">
<Image x:Name="PdfImage" Aspect="AspectFill" IsVisible="true"/>
</StackLayout>
In Code Behind(C#):
byte[] imageAsBytes = Constant.jsonPDF;
var stream1 = new MemoryStream(imageAsBytes);
PdfImage.Source = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
imagePanel.Children.Add(PdfImage);
But My problem is image is not displaying.
Can anybody tell me what I'm doing wrong. Any help would be greatly appreciated.
(XAML):
<Image Grid.Row="1" x:Name="IncidentImageData" Grid.ColumnSpan="4" BackgroundColor="DarkGray" Aspect="AspectFill" WidthRequest="50" HeightRequest="175"/>
viewModel.SImageBase64 is a byte[]
Code Behind(C#):
var stream1 = new MemoryStream(viewModel.SImageBase64);
IncidentImageData.Source = ImageSource.FromStream(() => stream1);
simply i have done like this and image has shown.
A Potential Fix
I know this thread is 2 years old now but I thought i'd post a working solution here for anyone who's also struggling with this. Just spent half a day researching and trying to solve an identical problem, the way the code was written on this post helped me greatly as it is almost 100% correct. You just need to provide the MemoryStream as a return from a lambda function within the FromStream() method.
Change this:
PdfImage.Source = ImageSource.FromStream(() => new MemoryStream(imageAsBytes));
To:
PdfImage.Source = ImageSource.FromStream(() =>
{
return new MemoryStream(imageAsBytes);
});
And the snippet should be working as of Xamarin Forms 5.0.0.2012
Full Code:
byte[] imageAsBytes = Constant.jsonPDF;
PdfImage.Source = ImageSource.FromStream(() =>
{
return new MemoryStream(imageAsBytes);
});
imagePanel.Children.Add(PdfImage);
Use this Code :
imgUserImage.Source = ImageSource.FromStream(() => new MemoryStream(userList.Single().ProfilePhoto));
Here profile photo type is byte[]
public byte[] ProfilePhoto { get; set; }

Add image in arraylist

I have to create a WPF app. which collects strings and images in rows. I am not sure if I could use multidimedional array or ArrayList but I cannot figure out how to insert the image into the array. Anyone can help me?
So if you want 1 Image against a variable number of string's
your Image becomes the Key of the Dictionary and the List<string> it's corresponding Value.
public Dictionary<Image, List<string>> MyCollection { get; private set; }
...
// Initialisation
MyCollection = new Dictionary<Image, List<string>>();
// Adding new Row
var tempImage = new Image();
MyCollection.Add(tempImage, new List<string>(){"A", "B", "C"});
// Modifying existing row -- for `Key` tempImage we'll add a string "D" and remove string "A"
List<string> existingValues = MyCollection[tempImage];
existingValues.Add("D");
existingValues.Remove("A");
// Removing rows
MyCollection.Remove(tempImage);
You can download this sample from Here. Hope that clarifies some of the usage ideas. I'd suggest looking at some Simple Examples to get a better understanding of how you can use Dictionary<...> to achieve your requirements.

Silverlight 5 datagrid is missing data

I am trying to bind an xml data set to a Silverlight data grid. There are 21 rows in my xml The grid shows the heading ok and the 21 rows but the rows show no data. If I look at the ItemsSource property it shows the row date as being there.
I am having a problem posting all the code because of the edits that Stack Overflow does. Here is the key piece. If you need to see anything else, I will post it as comments.
grdData.ItemsSource = cloData.LoadData("Sample.xml")
public class clsData
{
public System.Collections.IEnumerable LoadData(string pName)
{
XDocument nutritionsDoc = XDocument.Load(pName);
List<Nutrition> data = (from nutrition in nutritionsDoc.Descendants("Nutrition")
select new Nutrition
{
Group = nutrition.Attribute("Group").Value,
Name = nutrition.Attribute("Name").Value,
Quantity = nutrition.Attribute("Quantity").Value
}).ToList();
return data;
}
}
What am I missing?
I just made the nutrition class a public class and it was magically solved.
Bob

Providing the WPF designer with an image at DesignTime

This is a restatement of my question, the revision history contains the original mess.
What it boils down to is "How do I get the application's directory from my WPF application, at design time?"
Which duplicates the question here so if you happen to be passing by please vote to close, thanks.
Do you need the image to be "Content - Copy if newer"? If you switch it to "Resource" you can use the following path to reference the file:
"/MyImage.JPG"
or a longer version
"pack://application:,,,/MyImage.JPG"
given that the image is in the root of the project, otherwise just change the URI to
"/Some/Path/MyImage.JPG"
UPDATE 1:
For me, the longer pack uri syntax works with an image marked as "Content - Copy if newer" as well. However, the shorter syntax does not work. I.e:
This works:
"pack://application:,,,/MyImage.JPG"
This does NOT work:
"/MyImage.JPG"
I my example I added the image to the root of the project, and marked it as "Content". I then bound the design time data context to a view model with a property returning the longer pack URI above. Doing that results in the Content image being shown correctly at design time.
UPDATE 2:
If you want to load a bitmap source from a pack uri, you can do so by using another overload of the BitmapFrame.Create which takes an URI as the first parameter.
If I understand your problem correctly you get the string with the pack uri as the first item in the object array that is passed to your converter. From this string you want to load a BitmapSource.
Since the string contains a pack URI, you can create an actual URI from the string and then use that URI to load the BitmapSource:
var imagePath = values[0] as string;
// ...
try
{
var packUri = new Uri(imagePath);
BitmapSource bitmap = BitmapFrame.Create(packUri, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
{
// ...
}
}
}
Just return the exact path of the image from your entity in ImagePath property, such as ..
"C:\MyImage.JPG"
..
OR
..
"C:\MyApp\bin\Debug\MyImage.JPG"
Then your binding (i.e. <Image Source="{Binding ImagePath}" />) in .xaml will start working..
I solved it by leveraging the clevers found in this stackoverflow answer.
public class DMyViewModel : PhotoViewModelBase
{
public override string ImagePath
{
get
{
string applicationDirectory =
(from assembly in AppDomain.CurrentDomain.GetAssemblies()
where assembly.CodeBase.EndsWith(".exe")
select System.IO.Path.GetDirectoryName(assembly.CodeBase.Replace("file:///", ""))
).FirstOrDefault();
return applicationDirectory + "\\MyImage.JPG";
}
}
}

Resources