in my wp7 application i am selecting image from media library and i want to get base64 string of that image because i am sending it to my wcf service to create image on server. the code for getting base64 string is as follows:
void taskToChoosePhoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
fileName = e.OriginalFileName;
selectedPhoto = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
imgSelected.Source = selectedPhoto;
int[] p = selectedPhoto.Pixels;
int len = p.Length * 4;
result = new byte[len]; // ARGB
Buffer.BlockCopy(p, 0, result, 0, len);
base64 = System.Convert.ToBase64String(result);
}
}
but at server this code creates image file but in the format is invalid. I cross validated the base64 string but i think app is giving wrong base64string what could be the reason please help to find out the problem.
You are sending base64-encoded pixels on the server. I'm not sure that this is what you need. How about converting Stream to the base64 string?
var memoryStream = new MemoryStream();
e.ChosenPhoto.CopyTo(memoryStream);
byte[] result = memoryStream.ToArray();
base64 = System.Convert.ToBase64String(result);
Related
I am trying to resample a JPG image from 300dpi to 150dpi and am getting back a zero-length file.
Controller's ActionResult:
public ActionResult ViewImage(string file, int dpi = 300, bool log = true)
{
FileExtensions fileExtensions = new FileExtensions();
ImageExtensions imageExtensions = new ImageExtensions();
FileModel fileModel = fileExtensions.GetFileModel(file);
string contentType = fileModel.FileType;
byte[] fileData = fileModel.FileData;
string fileName = Path.GetFileNameWithoutExtension(fileModel.FileName) + "_" + dpi + "DPI" + Path.GetExtension(fileModel.FileName);
FileStreamResult resampledImage = imageExtensions.ResampleImage(fileData, contentType, dpi);
resampledImage.FileDownloadName = fileName;
return resampledImage;
}
ResampleImage method:
public FileStreamResult ResampleImage(byte[] fileData, string contentType, int targetDPI)
{
MemoryStream outputStream = new MemoryStream();
using (Stream sourceStream = new MemoryStream(fileData))
{
Image image = new Image(sourceStream);
image.HorizontalResolution = targetDPI;
image.VerticalResolution = targetDPI;
JpegEncoder jpegEncoder = new JpegEncoder();
jpegEncoder.Quality = 100;
image.Save(outputStream, jpegEncoder);
}
FileStreamResult file = new FileStreamResult(outputStream, contentType);
return file;
}
I thought I best answer here since we've already dealt with it on the issue tracker.
ImageProcessorCore at present (2016-08-03) is alpha software and as such is unfinished. When you were having the issue, horizontal and vertical resolution was not settable in jpeg images. This is now solved.
Incidentally there are overloads that allow saving as jpeg without having to create your own JpegEncoder instance.
image.SaveAsJpeg(outputStream);
Saving base64String as image on FTP Server is saving it as corrupted file.
I am doing following things
converted base64String into byte[].
Initialized MemoryStream with byte converted in above step.
Opened stream from FTP
Write stream on ftp.
Below is the code
public bool WriteFromBase64ToFile(string base64, string path, string fileName)
{
bool result = false;
using (FtpClient ftp = new FtpClient())
{
// setting ftp properties with required values.
ftp.ReadTimeout = 999999999;
ftp.Host = host;
ftp.Credentials = new System.Net.NetworkCredential(username, password);
ftp.Port = Convert.ToInt32(port);
ftp.DataConnectionType = FtpDataConnectionType.AutoPassive;
ftp.Connect();
ftp.ConnectTimeout = 1000000;
// converting base64String into byte array.
byte[] file = Convert.FromBase64String(base64);
if (ftp.IsConnected)
{
int BUFFER_SIZE = file.Length; // 64KB buffer
byte[] buffer = new byte[file.Length];
// Initializing MemoryStream with byte converted from base64String.
MemoryStream ms = new MemoryStream(buffer);
using (Stream readStream = ms)
{
fileName = fileName.ReplacingSpecialCharacterswithEntities();
// Getting stream from ftp and then writing it on FTP server.
using (Stream writeStream = ftp.OpenWrite(path + "/" + fileName+".jpg", FtpDataType.Binary))
{
while (readStream.Position < readStream.Length)
{
buffer.Initialize();
// Reading stream
int bytesRead = readStream.Read(buffer, 0, BUFFER_SIZE);
// Writing stream
writeStream.Write(buffer, 0, bytesRead);
}
// flushing stream.
writeStream.Flush();
}
}
}
}
result = true;
return result;
}
In my Windows Phone7.1 App Iam loading a HTML file from local path in a WebBrowser. For this I
converted a PNG Image to base64 format using the below code and the problem is base 64 format of image path is not loading the image in the webbrowser.
Please help me where i made mistake?
string s = "data:image/jpg;base64,";
imgStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NewUIChanges.Htmlfile.round1.png");
byte[] data = new byte[(int)imgStream.Length];
int offset = 0;
while (offset < data.Length)
{
int bytesRead = imgStream.Read(data, offset, data.Length - offset);
if (bytesRead <= 0)
{
throw new EndOfStreamException("Stream wasn't as long as it claimed");
}
offset += bytesRead;
}
base64 = Convert.ToBase64String(data);
Stream htmlStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("NewUIChanges.Htmlfile.equity_built.html");
StreamReader reader = new StreamReader(htmlStream);
string htmlcontent = reader.ReadToEnd();
htmlcontent = htmlcontent.Replace("round1.png", s + base64);
wb.NavigateToString(htmlcontent);
If you have no error, that data contains your image, and round1.png exist in htmlcontent, then it's just probably a image type error, try this:
string s = "data:image/png;base64,";
When i use this function to save image(fetch from net) to IsolatedStorage, i found the file size is larger than that i save from the webbrowse.
public static bool CreateImageFile(string filePath, BitmapImage bitmapImage)
{
//StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
using (isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
string directoryName = System.IO.Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(directoryName) && !isolatedStorage.DirectoryExists(directoryName))
{
isolatedStorage.CreateDirectory(directoryName);
}
if (isolatedStorage.FileExists(filePath))
{
isolatedStorage.DeleteFile(filePath);
}
//bitmapImage
using (IsolatedStorageFileStream fileStream = isolatedStorage.OpenFile(filePath, FileMode.Create, FileAccess.Write))
{
bitmapImage.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(bitmapImage);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
fileStream.Close();
}
}
return true;
}
Is that ok to save png images using WriteableBitmap.SaveJpeg(...)?
And is there any function to get the length of BitmapImage?
If it is a PNG, why would you use SaveJpeg to actually store it? Why not simply use the standard "data-to-file" approach? If it is already encoded as a PNG, all you need to do is store the content.
Read more here:
How to: Store Files and Folders for Windows Phone
Writing Data (Windows Phone)
Convert to byte array
byte[] data;
using (MemoryStream ms = new MemoryStream()
{
bitmapImage.SaveJpeg(ms, LoadedPhoto.PixelWidth, LoadedPhoto.PixelHeight, 0, 95);
ms.Seek(0, 0);
data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
ms.Close();
}
Then just get the size of the byte array and convert to something more reasonable (KB, MB...)
I'm having a really interesting problem to solve:
I'm getting a static google map image, with an URL like this.
I've tried several methods to get this information:
Fetching the "remote resource" as a ByteArrayOutputStream, storing the Image in the SD of the Simulator, an so on... but every freaking time I get an IlegalArgumentException.
I always get a 200 http response, and the correct MIME type ("image/png"), but either way: fetching the image and converting it to a Bitmap, or storing the image in the SD and reading it later; I get the same result... the file IS always corrupt.
I really belive its an encoding problem, or the reading method (similar to this one):
public static Bitmap downloadImage(InputStream inStream){
byte[] buffer = new byte[256];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (inStream.read(buffer) != -1){
baos.write(buffer);
}
baos.flush();
baos.close();
byte[] imageData = baos.toByteArray();
Bitmap bi = Bitmap.createBitmapFromBytes(imageData, 0, imageData.length, 1);
//Bitmap bi = Bitmap.createBitmapFromBytes(imageData, 0, -1, 1);
return bi;
}
The only thing that comes to mind is the imageData.lenght (in the response, the content length is: 6005 ), but I really can't figure this one out.
Any help is more than welcome...
try this way:
InputStream input = httpConn.openInputStream();
byte[] xmlBytes = new byte[256];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (len = input.read(xmlBytes)))
{
raw.append(new String(xmlBytes, 0, len));
size += len;
}
value = raw.toString();
byte[] dataArray = value.getBytes();
EncodedImage bitmap;
bitmap = EncodedImage.createEncodedImage(dataArray, 0,dataArray.length);
final Bitmap googleImage = bitmap.getBitmap();
Swati's answer is good. This same thing can be accomplished with many fewer lines of code:
InputStream input = httpConn.openInputStream();
byte[] dataArray = net.rim.device.api.io.IOUtilities.streamToBytes(input);
Bitmap googleImage = Bitmap.createBitmapFromBytes(dataArray, 0, -1, 1);