I have created a basic steganography application for windows phone 8 that works fine on the emulator but I get an error when using a device. With the emulator I can save a byte[] as an image as shown below:
byteArrayTextandImage = EncodeText(byteArrayInputImageEncode,byteArrayInputText, 4096);
using (var s = new MemoryStream())
{
Picture pic = library.SavePicture(Guid.NewGuid().ToString(), byteArrayTextandImage);
}
I tried to get around it by using a WritableBitmap as shown below:
using (var s = new MemoryStream())
{
WriteableBitmap wb = new WriteableBitmap((BitmapSource)bmp);
wb.SaveJpeg(s, bmp.PixelWidth, bmp.PixelHeight, 0, 72);
s.Seek(0, SeekOrigin.Begin);
var pic = library.SavePicture(Guid.NewGuid().ToString() + ".jpg", s);
MessageBox.Show(pic.Name);
}
however this is modifying the image and removing the text I had encoded within it. Has anybody encountered a problem like this before? Why would the emulator work fine but not on a device? I have checked the manifest and I have the necessary capabilities checked.
Thanks for any help anybody can provide.
Related
I have a .NET Core 2.2 web app where I am storing user images in a SQL Server database. When I save the file as is, it displays in the web page with no problems.
After that I wanted to resize the image when the user uploads the file and installed Imagesharp package and used the following code to resize the image. The code runs perfectly but when the use logs in. the image is not displayed.
My code to resize and store the image into the database is:
Image Processing Methods
public Stream ResizeImage(Image<Rgba32> sourceImage, int destHeight, int destWidth)
{
sourceImage.Mutate<Rgba32>(ctx => ctx.Resize(destWidth,destHeight));
Stream outputStream = new MemoryStream();
sourceImage.Save(outputStream, new JpegEncoder());
return outputStream;
/*return sourceImage.
.Crop(new Rectangle(sourceX, sourceY, sourceWidth,
sourceHeight))
.Resize(destinationWidth, destinationHeight);*/
}
My code to store the image:
if (ModelState.IsValid)
{
if (ProfileImage != null)
{
var stream = ProfileImage.OpenReadStream();
Image<Rgba32> theimage = _imageProcessor.GetImageFromStream(stream);
var outstream = _imageProcessor.ResizeImage(theimage, 100, 100);
//Input.Image = commonData.ConvertToBytes(ProfileImage);
Input.Image = commonData.ConvertStreamToBytes(outstream);
}
var user = new ApplicationUser
{
UserName = Input.Email,
Email = Input.Email.ToLower().Trim(),
FirstName = Input.FirstName,
LastName = Input.LastName,
Image = Input.Image,
AccountDisabled = true
};
}
I am trying to display the image in html after converting it to the base64string as follows:
userView.UserImageBytes = new string(Convert.ToBase64String(userView.TheUser.Image));
My HTML markup to display the image:
<img src="data:image/jpg;base64,#Model.UserImageBytes" alt="No Image" />
The above code works fine but the stored image is not displayed.
How to display the image properly. Any help is appreciated.
After this line:
sourceImage.Save(outputStream, new JpegEncoder());
outputStream is has its .Position set after the last written byte. You might, for instance, write more data to that stream after the image. In order for another bit of code to read the image, you need to reposition outputStream before you return it. eg
outputStream.Position = 0;
return outputStream;
I have a Universal Windows application that hosts a main menu. I want a plugin architecture, where the menu items are added from class libraries.
But I can't seem to load images correctly. I can't get the ms-appx:/// working, and when I try to add the images as an embedded resource, it hangs:
var assembly = typeof(CookModule).GetTypeInfo().Assembly;
using (var imageStream = assembly.GetManifestResourceStream("My.Namespace.Folder.ImageName-100.png"))
using (var raStream = imageStream.AsRandomAccessStream())
{
var bitmap = new BitmapImage();
bitmap.SetSource(raStream); //<- Hangs here
I get no exceptions, errors in the output or anything. It just hangs there, and the app simply doesn't load the page.
I have also tried:
var bitmap = new BitmapImage(new Uri("/Folder/ImageName-100.png"));
I'm missing something similar to the WPF pack uri's where I can state which assembly to load the image from.
What is the correct (and working) way of adding a image resource to a Page from a class libary? (Or does anyone have a working example of ms-appx where the image is in a class library)
I can reproduce this issue. Current workaround I used is copying the resource stream to .NET memory stream.
var assembly = typeof(CookModule).GetTypeInfo().Assembly;
using (var imageStream = assembly.GetManifestResourceStream("UWP.ClassLibrary.210644575939381015.jpg"))
using (var memStream = new MemoryStream())
{
await imageStream.CopyToAsync(memStream);
memStream.Position = 0;
using (var raStream = memStream.AsRandomAccessStream())
{
var bitmap = new BitmapImage();
bitmap.SetSource(raStream);
display.Source = bitmap;
}
}
I have 2 solutions in this project. A windows forms solution and a Windows 8.1 Tablet project.
This is what's supposed to happen:
User takes a picture using the tablet and uploads it to a MySQL database in the form of a byte array.
User starts up the windows forms application and loads the byte array from the MySQL database.
It then converts the byte array to an image which is placed in a picturebox.
I'm storing the byte array like this:
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
Size aspectRatio = new Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
var readStream = fileStream.AsStreamForRead();
byte[] pixeBuffer = new byte[readStream.Length];
await readStream.ReadAsync(pixeBuffer, 0, pixeBuffer.Length);
}
The byte array is successfully stored in my database.
I'm running into a problem when converting the byte array into a WinForms Image.
This is my code:
using (var ms = new MemoryStream(bytes))
{
Image i = Image.FromStream(ms);
return i;
}
This gives me an invalid parameter exception.
I'm guessing it's something with the image format? I'm really new to streams though so I have no idea.
Any help is welcome!
PS: I know storing in the SQL database runs perfectly since I can store and load images perfectly using the WinForms application only.
Have you tried setting the position of the MemoryStream back to the beginning before trying to create the Image...
ms.Seek(0, SeekOrigin.Begin);
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap
(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
return ms.ToArray();
}
Try it ,
it's working with me
When I try to Serialize some images using the BinaryFormatter, I'll get a ExternalException - A generic error occurred in GDI+." After scratching my head for awhile, I decided to create a simple test project to narrow down the problem:
static void Main(string[] args)
{
string file = #"C:\temp\delme.jpg";
//Image i = new Bitmap(file);
//using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
byte[] data = File.ReadAllBytes(file);
using(MemoryStream originalms = new MemoryStream(data))
{
using (Image i = Image.FromStream(originalms))
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
// Throws ExternalException on Windows 7, not Windows XP
bf.Serialize(ms, i);
}
}
}
}
For specific images, I've tried all sorts of ways of loading the image and I could not get it to work under Windows 7, even when running the program as Administrator.
I've copied the exact same executable and image into my Windows XP VMWare instance and I have no problems.
Anyone have any idea of why for some images it doesn't work under Windows 7, but works under XP?
Here's one of the images:
http://www.2shared.com/file/7wAXL88i/SO_testimage.html
delme.jpg md5: 3d7e832db108de35400edc28142a8281
As the OP pointed out, the code provided throws an exception that seems to be occurring only with the image he provided but works fine with other images on my machine.
Option 1
static void Main(string[] args)
{
string file = #"C:\Users\Public\Pictures\delme.jpg";
byte[] data = File.ReadAllBytes(file);
using (MemoryStream originalms = new MemoryStream(data))
{
using (Image i = Image.FromStream(originalms))
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
// Throws ExternalException on Windows 7, not Windows XP
//bf.Serialize(ms, i);
i.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); // Works
i.Save(ms, System.Drawing.Imaging.ImageFormat.Png); // Works
i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // Fails
}
}
}
}
It could be that the image in question was created with a tool that added some additional information that is interfering with the JPEG serialization.
P.S. The image can be saved to memory stream using BMP or PNG format. If changing the format is an option, then you can try out either of these or any other format defined in ImageFormat.
Option 2
If your goal is just to get the contents of the image file into a memory stream, then doing just the following would help
static void Main(string[] args)
{
string file = #"C:\Users\Public\Pictures\delme.jpg";
using (FileStream fileStream = File.OpenRead(file))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
}
}
Although the Bitmap class is marked as [Serializable], it does not actually support serialisation. The best you can do is serialise the byte[] containing the raw image data and then re-create it using a MemoryStream and the Image.FromStream() method.
I can't explain the inconsistent behaviour you're experiencing; for me, it fails unconditionally (although I first discovered this when trying to marshal images between different app domains, rather than manually serialising them).
I don't know for sure but I would lean towards different security models for XP vs Windows 7. Image inherits from System.MarshalByRefObject. There is probably proxying going on between application domains when serialization is performed. This proxying might be forbidden in Windows 7.
http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject%28v=vs.71%29.aspx
I have some c# code that gets an image from a webpage then downloads it to my local machine. This is done in the background 1/sec. If I leave this running it works fine and my pictures get updated correctly. These pictures are basically feeds from a camera. I want to put these pictures into a picturebox or some other control so that I can display the images as if they were a camera feed. However when I tried doing this I've got errors saying the image is being used so I can not load it into my picturebox. Is there a better way to do this?
Thanks,
byte[] lnBuffer;
byte[] lnFile;
HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create(uri);
lxRequest.Credentials = credentials;
using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse())
{
using (BinaryReader lxBR = new BinaryReader(lxResponse.GetResponseStream()))
{
using (MemoryStream lxMS = new MemoryStream())
{
lnBuffer = lxBR.ReadBytes(1024);
while (lnBuffer.Length > 0)
{
lxMS.Write(lnBuffer, 0, lnBuffer.Length);
lnBuffer = lxBR.ReadBytes(1024);
}
lnFile = new byte[(int)lxMS.Length];
lxMS.Position = 0;
lxMS.Read(lnFile, 0, lnFile.Length);
lxMS.Close();
lxBR.Close();
}
}
lxResponse.Close();
}
using (System.IO.FileStream lxFS = new FileStream("images/camppic1.jpg", FileMode.Create))
{
lxFS.Write(lnFile, 0, lnFile.Length);
lxFS.Close();
}
This is what I use to create the file. Then in the same method after this code I do this:
image = Image.FromFile("C:\camppic1.jpg");
pictureBox23.Image = image;
If you need the file, then load the file content and copy to a MemoryStream and use Image.FromStream. If you don't need the file, you could skip it and use the MemoryStream directly from the downloading... (Faster since no disc access would be needed.)