I have an .NET Core console application which does some update stuff to my CouchDB.
Now I have to add multiple attachments (in this case images) to my doc.
Here (https://docs.couchdb.org/en/stable/api/document/common.html#attachments) in point 1.4.1.1.4 they describe the way, but I get a Bad Request, I think my json is not perfect.
So I have a list of images that I convert and then send to DB, here is my code:
List<ImageFromApi> imagesFromApi = new List<ImageFromApi>();
string base64String;
foreach (var image in Images)
{
using (image)
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
base64String = Convert.ToBase64String(imageBytes);
}
}
ImageFromApi Imagebuffer = new ImageFromApi() {
content_type = "image/*",
data = base64String
};
imagesFromApi.Add(Imagebuffer);
DocAttachments bufferData = new DocAttachments() {imagesFromApi = imagesFromApi };
newImages._attachments = bufferData;
}
string imagesJson = JsonConvert.SerializeObject(newImages);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(imagesJson);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
My Json from this code looks like this:
I see the difference between mine and the one from the documentation, but I dont know how to change my json correctly.
Any solutions?
So that nobody had a solution, i tried something around and find a way to achieve what i need. I made a new Attachment and added each image manually.
Here is an example of the first image:
Attachments attBuffer = new Attachments();
using (imagesFromApi[0])
{
using (MemoryStream m = new MemoryStream())
{
partImgs[0].Save(m, partImgs[0].RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
base64String = Convert.ToBase64String(imageBytes);
}
}
attBuffer.Hood = new Hood()
{
content_type = "image/jpeg",
data = base64String,
};
As you can see, i created any of my images as a class and then mapped the list to it. I think this is not the best way, but it works for me, so better than nothing.
Hope it helps you as well.
I'm using Java Script to convert Image to string and store in the field value. As we can see the below Javascript:
// Getting the Object
var oFile = this.getDataObjectContents("Test1");
//object into the string
var cFile = util.stringFromStream(oFile, "utf-8");
// storing in the field
this.getField("Text2").value = cFile;
I'm reading all the field On the pdf and I'm able to get the field Value, but when I'm trying to write it, in the Server/Local machine I'm not able to write the image. I'm using the below code.
byte[] br;
// (cc.Value)// value of the field
br = Encoding.ASCII.GetBytes(cc.Value);
//br= imgToByteArray
byte[] pdfdata = Encoding.ASCII.GetBytes(cc.Value);
Stream streamed = new MemoryStream(pdfdata);
Stream InputStream = streamed;
byte[] result;
using (var streamReaderWE = new MemoryStream())
{
InputStream.CopyTo(streamReaderWE);
result = streamReaderWE.ToArray();
File.WriteAllBytes(fileNameEEEE, result);
}
I'm not able to return the Image
I'm having troubles to make my program work correctly - here I explain :
I have, on one hand a C# WinForms app which launches an instance of IE by using the "Navigate" method : myWebBrowser.Navigate(myUrl, "_blank", intarray, "");, with intarray defined like this : byte[] intarray = BitConverter.GetBytes(id);. On this side, it works.
On the other side, I have an ASP .NET WebForms application which has to retrieve this intarray. I've tried this.
if (HttpContext.Current != null)
{
if (Session["Authenticated"] == null)
{
var current = HttpContext.Current;
byte[] postdata = getpostdata(current);
}
}
private byte[] getpostdata(HttpContext CurrentContext)
{
MemoryStream ms = new MemoryStream();
CurrentContext.Request.InputStream.CopyTo(ms);
byte[] postdata = ms.ToArray();
return postdata;
}
// Convert a byte array to an Object
public int ByteArrayToInt(byte[] arrBytes)
{
if (BitConverter.IsLittleEndian) Array.Reverse(arrBytes);
int i = BitConverter.ToInt32(arrBytes, 0);
return i;
}
The problem seems to be in retrieving the Data in the getpostdata(HttpContext) function... I get a byte array with length = 0 instead of the one which is sent with length = 4...
Does anyone know how to make it work ?
Yann
var current = HttpContext.Current;
var sr = new StreamReader(Request.InputStream, Encoding.Default);
var postdata = sr.ReadToEnd();
above
I'm looking to convert this piece of code to c#:
var local1:ByteArray= new ByteArray();
var auth:String = root.loaderInfo.parameters.auth as String;
var key0:String = root.loaderInfo.parameters.key0 as String;
var key1:String = root.loaderInfo.parameters.key1 as String;
var key2:String = root.loaderInfo.parameters.key2 as String;
var key3:String = root.loaderInfo.parameters.key3 as String;
local1.writeUnsignedInt(parse(auth));
local1.writeUnsignedInt(parse(key0));
local1.writeUnsignedInt(parse(key1));
local1.writeUnsignedInt(parse(key2));
local1.writeUnsignedInt(parse(key3));
trace(local1)
You see how I directly print the byte array without converting it to a string. How can you do that in c#? Is suppose to print out something like this: TV˜ 3 R j i
If the array contains something that can be interpreted as character codes, then you can decode the bytes into text. For example:
string localText = Encoding.Default.GetString(local1);
The encoding to use would depend on how the text was converted to bytes in the first place.
You can use a MemoryStream and a BinaryWriter to put the integers in an array. Example:
string auth = "1"; // example data, would come from your object
string key0 = "2";
byte[] local1;
using (MemoryStream m = new MemoryStream()) {
using (BinaryWriter w = new BinaryWriter(m)) {
w.Write(Int32.Parse(auth));
w.Write(Int32.Parse(key0));
}
local1 = m.ToArray();
}
foreach(var g in local1)
{
Console.WriteLine((char)g);
}
I'm trying to convert a byte array to a bitmap but it always shows me:
System.ArgumentException: Parameter is not valid.
My code is as follows:
I'm passing the bytes through a webservice with:
string DecodedString = string.Empty;
DecodedString = System.Text.Encoding.GetEncoding(1251).GetString(bytes);
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
and in my webPage:
byte[] bytes = (Byte[])System.Text.Encoding.GetEncoding(1251).GetBytes(XmlConvert.DecodeName(xDocument.SelectSingleNode("Response/Images/Photo").InnerText));
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms);//(System.Drawing.Image.FromStream(ms));
Try passing the string as a Base64:
string DecodedString = string.Empty;
DecodedString = System.Convert.ToBase64String(bytes)
sResult = sResult + "<Photo>" +XmlConvert.EncodeName(DecodedString) + "</Photo>";
...
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = System.Drawing.Image.FromStream(ms);
You also won't need to use XmlConvert to encode/decode the string.
I did it, with the help of all of you, here is my page code
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
System.Drawing.Bitmap b = new System.Drawing.Bitmap(ms); //(Bitmap)System.Drawing.Image.FromStream(ms);
System.Drawing.Imaging.FrameDimension frameDim;
frameDim = new System.Drawing.Imaging.FrameDimension(b.FrameDimensionsList[0]);
int NumberOfFrames = b.GetFrameCount(frameDim);
string[] paths = new string[NumberOfFrames];
for (int i = 0; i < NumberOfFrames; i++)
{
b.SelectActiveFrame(frameDim, i);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(b);
paths[i] = imagePathfile.Remove(imagePathfile.Length - 4, 4) + i.ToString() + ".gif";
bmp.Save(paths[i], System.Drawing.Imaging.ImageFormat.Gif);
//bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
bmp.Dispose();
}
Image1.Src = paths[0];
//Check if there's more than 1 image cause its a TIFF
if (paths.Length>1)
{
Image2.Src = paths[1];
}
I had a similar problem recently, but using Silverlight. I ended up needing to create a Custom HTTP Handler in order to pass the byte[] that defined the image back as a stream.
See http://www.dotnetcurry.com/ShowArticle.aspx?ID=220
Edit: This allows you to avoid worrying about XML encoding, and passes the image back in Binary form... YMMV
According to MSDN:
ArgumentException - The stream does not have a valid image format
I believe your problem is in the original byte[] array you are passing to the web service.
According to one of your comments, you did:
System.IO.FileStream fs = new System.IO.FileStream(sPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
int streamLength = Convert.ToInt32(fs.Length);
bytes = new byte[streamLength];
fs.Read(bytes, 0, streamLength);
fs.Read returns the number of bytes that have been read into the byte array; it doesn't always read the entire file!
Try using the StreamFile method from http://www.dotnetspider.com/resources/4515-convert-file-into-byte-array.aspx. (First result of Google search)
Try this:
byte[] bytes = System.Convert.FromBase64String(xDocument.SelectSingleNode("Response/Images/Photo").InnerText);
System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = imageConverter.ConvertFrom(bytes) as Image;
System.Drawing.Bitmap b = new System.Drawing.BitMap(image);
EDIT
Take a look at this:
Transfer any files on Web services by c#
actually i had been meet this problem, In my case, when i use IE browser, it is ok but when use another browser it always have the same error.
"Parameter is not valid exception is always happening in the same line of code:
System.Drawing.Image.FromStream(ms));"
So i think it seems this issue depend on browser and type of image (JPEG,JPEG2000).
Here is some code I used converting bytes to an image for a unit test:
protected override Image LoadImage()
{
//get a temp image from bytes, instead of loading from disk
//data:image/gif;base64,
byte[] bytes = Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
To my understanding, the image can not be shown because the format of the image's bytes is not correct. Every image format has its own head or something.