How to get a C# Image over to Monotouch - image

I am connecting from monotouch through wcf to my windows c# host and wish to stream an image back to monotouch so I can display this.
My image is held in an System.Drawing.Image object which is not available in monotouch (it uses UIImage).
I was hoping to convert the Image on the host to a string like so:
Image im = Image.FromFile(path);
MemoryStream ms = new MemoryStream();
im.Save(ms, im.RawFormat);
byte[] array = ms.ToArray();
return Convert.ToBase64String(array);
And then using the opposite within MonoTouch to get my Image back again:
byte[] array = Convert.FromBase64String(imageString);
Image image = Image.FromStream(new MemoryStream(array));
return image;
This works fine in a 'pure' .net environment but monotouch doesn't recognise the Image object so it fails on that end.
How can I convert the byte[] back into a UIImage?
I tried things like this:
UIImage img = (UIImage)UIImage.FromObject(bytes);
to no avail...
Any help much appreciated!

Instead of passing im.RawFormat, try using one of:
ImageFormat.Bmp
ImageFormat.Png
Depending on which format your images usually are. These are in System.Drawing.Imaging, see here.
This might cause trouble for other client applications, I would recommend having the client send something to determine what format the server returns.

Related

How to get image from random byte array

I'm working with decoder for Apple CarPlay which originally is using WebRTC and html video as display for it. I'm trying to replace html with Fyne image refresh.
Current source code looks like that
duration := time.Duration((float32(1) / float32(fps)) * float32(time.Second))
if videoTrack != nil {
videoTrack.WriteSample(media.Sample{Data: data.Data, Duration: duration})
}
where videoTrack is:
videoTrack *webrtc.TrackLocalStaticSample
I've tried to move data.Data (since it's byte[]) into image converter, but I guess there's some more for that.
Im looking for some help in transporting these byte[] into image compression because that's the format Fyne is using, but without any success. Can anyone give me some hint in that?
You can either load the byte[] to an image using standard go image package (blocking operation) or you can pass it to Fyne as a resource).
To do the latter try canvas.NewImageFromResource(fyne.NewStaticResource(“streamName.png”, data)).
After this setup you can set the Image or Resource on your image and call 'Refresh()` to update the display.

Xamarin - how to reset image cache for a specific image

In my Xamarin app I upload a new "user profile" image on the server, then I try to update the image with the new version of the image (Noticed that the image uri is the still the same).
There is an image cache provided by Xamarin, I need to invalidate it to force the image to reload from the server. But it seems that the Image cache cannot be invalidated ! I find no solution !
I have try several solutions, but find no way ! Even when I restart the application I get the old version of the image.
I have try some stuffs like this :
(MediaImageSource as UriImageSource).CacheValidity = new TimeSpan(-1);
FFImageLoading.Forms.CachedImage.InvalidateCache(MediaImageSource, FFImageLoading.Cache.CacheType.All, true);
FFImageLoading.ImageService.Instance.InvalidateCacheAsync(FFImageLoading.Cache.CacheType.All);
But nothing work, any idea is welcome ? Thx
I do the following:
// this.Img is the FFImageLoading.CachedImage in my view
var source = this.Img.Source as FileImageSource;
// Reset cache using the global instance (the key is the file name, I assume it is the uri for UriImageSource)
await ImageService.Instance.InvalidateCacheEntryAsync( source.File, CacheType.All, true );
// Reassign the image source (since the binding has not changed per se, the UI may miss the change otherwise)
this.Img.Source = new FileImageSource(...);
This reloads the image and FFImageLoading even does a nice fade animation when it changes.
There is actually a static method in CachedImage that accepts any kid of ImageSource, so there is no need to guess the key:
FFImageLoading.Forms.CachedImage.InvalidateCache(myImageSource, CacheType.All, true);

Alternatives to using a MovieClip or BitmapData for an image?

I've been trying for two days to find an alternative to loading an image into my current project. I am using Adobe Flash Professional CS6 as my IDE and Animation program. I would like to be able to display an image in my application. What I am trying to do is have the image display onto the screen, the user enters the PLU associated with the image, and if the PLU is right then they receive a point. I have everything else already to go, but I just can't find an efficient way to deal with loading the image.
Right now I'm using this to accomplish getting my image on the display:
var myDisp:Layer0 = new Layer0();
var bmp:Bitmap = new Bitmap(myDisp);
spDispBox.addChild(bmp);
The above code works just find, but the limitation I can't get around is that I'm going to have to import each image into the library and then consecutively code each part in. I wanted to stick to OOP and streamline this process, I just don't know where I should turn to in order to accomplish my project goal. I'm more than happy to give more information. Thanks in advance, everyone.
July, 26, 2014 - Update: I agree, now, that XML is the way to go. I'm just having a hard time getting the grasp of loading an external XML file. I'm following along, but still not quite getting the idea. I understand about creating a new XML data object, Loader, and URLRequest. It's just loading the picture. I've been able to get output by using trace in the function to see that the XML is loaded, but when I go to add the XML data object to the stage I'm getting a null object reference.
I'm going to try a few more things, I just wanted to update the situation. Thanks again everyone.
it seems like these images are in your FLA library. To simplify your code you can make a singleton class which you can name ImageFactory (factory design pattern) and call that when needing an image which will return a Sprite (lighter than a MovieClip)
spDispBox.addChild( ImageFactory.getImageA() ); // returns a Sprite with your image
and in your ImageFactory
public function getImageA():DisplayObject {
var image:Layer0 = new Layer0(); // image from the FLA library
var holder:Sprite = new Sprite();
holder.addChild( new Bitmap( image ) );
return holder;
}
also recommend using a more descriptive name than Layer0

Image capture using CameraCapture

I am using a sample code from Microsoft windows SDK (CameraCapture, which is found in C:\Program Files\Windows Mobile 6 SDK\Samples\PocketPC\CPP\win32\CameraCapture) to capture image using windows mobile. The program save a image into a file, but I am interested to store the image into memory rather than any saving into storage.
any suggestions?
I don't have access to that particular sample but I assume that the project is using the CaptureCameraDialog class.
http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.forms.cameracapturedialog_members.aspx
Unfortunately using this class will only return the image path. You don't state why you need to save it in memory rather than on the disk but if your intention is to do some basic processing then you could just load it from the disk once captured.
using (CameraCaptureDialog cameraCapture = new CameraCaptureDialog())
{
cameraCapture.ShowDialog();
//get the name of the last image taken
string fileName = cameraCapture.FileName;
//Load the image from disk into our image object
Image image = new Bitmap(fileName);
}
A word of caution here. I believe when saved to disk the images will be in a compressed format, but when loaded into memory they will be uncompressed. It is very easy to cause an out of memory exception when working with images in the compact framework so I wouldn't recommend holding lots of images in memory at once especially if working with a hi resolution camera.

DynamicPDF image quality loss

We are using a product called DynamicPDF to generate PDF's on the fly from dynamic data from a database. Their documentation says that their software leaves the image bytes intact and doesn't make any changes. Despite this, we have observed that the images we add seem to have quality loss on the resulting PDF output (at least that's how they look). So my question is what do I need to do with the DynamicPDF API to ensure that the image quality output is equal or close to what I put in?
We are using Version 5.1.2 Build 13650, below is the code that we use to add the image.
private void plcImageMain_LaidOut(object sender, PlaceHolderLaidOutEventArgs e)
{
if (e.LayoutWriter.RecordSets.Current.HasData)
{
string productId = e.LayoutWriter.RecordSets.Current["ProductId"].ToString();
string imgUrl = base.SetImageUrlParams(e.LayoutWriter.RecordSets.Current["ImageUrl"] as string, e.ContentArea.Width, e.ContentArea.Height);
System.Drawing.Bitmap bm = base.GetBitmap(imgUrl);
ceTe.DynamicPDF.PageElements.Image img = new ceTe.DynamicPDF.PageElements.Image(bm, 0, 0);
img.Height = e.ContentArea.Height;
img.Width = e.ContentArea.Width;
e.ContentArea.Add(img);
}
}
/// <summary>
/// Gets a bitmap from the requested image url
/// </summary>
/// <param name="imgCtrl"></param>
/// <param name="imgUrl"></param>
protected System.Drawing.Bitmap GetBitmap(string imgUrl)
{
// TODO: Add some validation to ensure the url is an image.
System.Net.WebRequest httpRequest = System.Net.HttpWebRequest.Create(imgUrl);
using (System.Net.HttpWebResponse httpResponse = httpRequest.GetResponse() as System.Net.HttpWebResponse)
using (Stream imgStream = httpResponse.GetResponseStream())
{
System.Drawing.Bitmap bm = System.Drawing.Bitmap.FromStream(imgStream) as System.Drawing.Bitmap;
return bm;
}
}
[Edit]
Here is the before and after screenshot.
[Edit]
Code using GetImage (why so slow?)
protected ceTe.DynamicPDF.Imaging.ImageData GetImageData(string imgUrl)
{
ImageData imgData = null;
using (System.Net.WebClient wc = new System.Net.WebClient())
{
imgData = ImageData.GetImage(wc.DownloadData(imgUrl));
}
return imgData;
}
GetImageData ("http://s7d2.scene7.com/is/image/SwissArmy/cm_vm_53900E--111mm_sol_front_a?fmt=jpeg&wid=400&hei=640");
All right, this looks like poor effort at resizing but it could just as well be your Acrobat reader doing it on screen, with the actual data being perfectly fine.
You should be able to select an image by clicking it in Reader (so it's highlighted blue) and then copy and paste it to an image editing program of your choice. That way, you should get the resource in original solution no matter what it's scaled down to.
There are also tools to extract images and other resources from PDFs, but I don't know one I can recommend offhand.
In regards to the DynamicPDF product, there is not any resizing or resampling done to the image as it is added to the PDF document. Pekka is actually right on with this. It is the reader that is visually representing the image with differing clarity (at different zoom levels).
If you are able to pull the image out of the PDF (as Pekka recommends above) you will see the image data is completely original and not modified.
One additional thing you can do to demonstrate this would be to take your original image, right click on it and select "Convert To Adobe PDF" (requires full Acrobat Pro). In that newly created PDF you would also visually see the same results.
One final thing worth noting is just a smalll inefficiency in the code you displayed above. Right now you are pulling the image content as a Stream, creating a bitmap out of that Stream object and then using that bitmap to create the DynamicPDF Image object. The recommended way to accomplish this would be to take the Stream object of the image that you are pulling from the URL, pass this into the DynamicPDF's ImageData Static method "GetImage". This GetImage method will return the ImageData object. Then use that ImageData to create your DynamicPDF Image object out of.
There are two clear advantages to loading the image this way. First is that you do not have the overhead involved with the System.Drawing.Bitmap object needing to separately process the image content (so in theory the app would run faster without this). And the second advantage is that the image content is added to the PDF in whatever native compression that it was originally in. As in the case of JPEG images, using the image’s native compression as opposed to the bitmap’s compression will result in a smaller output PDF file size. None of this will have any influence on the image quality of the output PDF but it could affect the efficiency and output PDF file size.
You were both right that it was Acrobat that was causing the fuzzy display. There is a setting in preferences called resolution, instead of using the System dpi setting by default Acrobat decided to use a custom dpi setting of 110 (I have no idea why!?!?). After setting it to system (in my case 96dpi) the images were crystal clear.

Resources