C# - Base64的字节数组映像会失败,不管我怎么努力 [英] C# - Base64 byte array to Image FAILS no matter what I try
问题描述
我无法从一个base64 EN codeD字节数组建立在C#中的图像/位图对象。
这里就是我处理:
我有一个前端,用户可以在裁剪图像。当用户选择通过输入图像[type = file]
,我的JavaScript code使用HTML5的的FileReader保存 DataUrl
(BASE64字符串)到隐藏字段
,与该作物的坐标和尺寸,一切都在形式的人一起发布
。
精华:
的base64数据,如果你想测试自己:
http://kristianbak.com/test_image.txt
- 的base64字符串被张贴到行动,并获得作为参数
为imageData code>
- 操作的字符串转换为一个base64字节数组,像这样:
-
字节[] = imageBytes Convert.FromBase64String(imageData.En codeTo64());
恩codeTo64扩展方法:
公共静态字符串连接codeTo64(此字符串TOEN code)
{
VAR TOEN codeAsBytes = Encoding.ASCII.GetBytes(TOEN code);
VAR的returnValue = Convert.ToBase64String(TOEN codeAsBytes);
返回的returnValue;
}
中的Base64字符串转换为一个字节数组后,我使用读字节到内存中的的MemoryStream
:
使用(VAR的ImageStream =新的MemoryStream(imageBytes,FALSE))
{
形象画像= Image.FromStream(的ImageStream); //的ArgumentException:参数无效。
}
我也曾尝试以下变化:
)
使用(VAR的ImageStream =新的MemoryStream(imageBytes))
{
位图图像=新位图(的ImageStream); //的ArgumentException:参数无效。
}
B)
使用(VAR的ImageStream =新的MemoryStream(imageBytes))
{
imageStream.Position = 0;
形象画像= Image.FromStream(的ImageStream); //的ArgumentException:参数无效。
}
C)
类型转换器的TypeConverter = TypeDescriptor.GetConverter(typeof运算(位图));
位图图像=(位图)typeConverter.ConvertFrom(imageBytes);
D)
使用这个方法:
私人位图GetBitmap(字节[] buf中)
{
Int16的宽度= BitConverter.ToInt16(BUF,18);
Int16的高度= BitConverter.ToInt16(BUF,22); 位图位图=新位图(宽,高); //的ArgumentException:参数无效。 INT IMAGESIZE =宽*高* 4;
INT headerSize = BitConverter.ToInt16(BUF,10); System.Diagnostics.Debug.Assert(IMAGESIZE == buf.Length - headerSize); INT偏移= headerSize;
对于(INT Y = 0; Y<高度; Y ++)
{
对于(INT X = 0; X<宽度; X ++)
{
bitmap.SetPixel(X,高度 - Y - 1,Color.FromArgb(BUF [偏移+ 3],BUF [偏移],BUF [偏移+ 1],BUF [偏移+ 2));
偏移+ = 4;
}
}
返回位图;
}
结论:
我觉得还有别的东西错了,我希望你能回答这个问题。
编辑:
前端code样本:
<脚本>
$(函数(){
VAR读卡器=新window.FileReader(); 功能readImage(文件回调){
reader.onload =功能(E){
VAR图像=新的图像();
image.onload =功能(imageEvt){
如果(typeof运算回调==功能){
回调(e.target.result);
}
};
image.src = e.target.result;
};
reader.readAsDataURL(文件);
} 附加$ J('#文件')。改变(函数(五){
var文件= e.target.files [0]; readImage(文件,功能(为imageData){
$('#为imageData)VAL(为imageData)。
});
});
});
< / SCRIPT>@using(Html.BeginForm(UploadImage,图像,FormMethod.Post,新{ENCTYPE =的multipart / form-data的}))
{
@ Html.ValidationSummary(真)
<输入名称=PostedImage.ImageData类型=隐藏ID =为imageDataVALUE =/> @ *在HTML $ C $的C在这里休息* @ < P>选择图像:其中; / P>
<输入类型=文件名称=文件ID =文件/> <输入类型=提交值=上传/>
}
控制器/操作的示例:
[HttpPost]
公众的ActionResultØpreT(PostedImage postedImage)
{
字符串为imageData = PostedImage.ImageData; 字节[] = imageBytes Convert.FromBase64String(imageData.En codeTo64()); 使用(VAR的ImageStream =新的MemoryStream(imageBytes,FALSE))
{
形象画像= Image.FromStream(的ImageStream);
}
}
我觉得你的问题是,你正在被张贴到控制器一个base64字符串,将它像ASCII,然后再转换为base64。
我想你需要改变这一行
字节[] = imageBytes Convert.FromBase64String(imageData.En codeTo64());
到
字节[] = imageBytes Convert.FromBase64String(为imageData);
从那里,你应该字节是正确的,你应该能够创建自己的图像
- 编辑 -
我把你的文本文档中,并提供加载到一个位图前分析它的样本数据。我能够将图像保存到我的硬盘,被斯巴达(走向绿色!)
欢迎给这个code试一试,看看会发生什么。
请注意为imageData正是所暴露在 http://kristianbak.com/test_image.txt 。我会提供的初始化,但它是一个pretty大串并可能打破东西。
字符串imageDataParsed = imageData.Substring(imageData.IndexOf('')+ 1);
字节[] = imageBytes Convert.FromBase64String(imageDataParsed);
使用(VAR的ImageStream =新的MemoryStream(imageBytes,FALSE))
{
位图图像=新位图(的ImageStream);
}
I'm having trouble creating an Image/Bitmap object in C# from a base64 encoded byte array.
Here's what I'm dealing with:
I have a frontend where a user can crop an image. When the user selects an image via an input[type=file]
, my javascript code uses HTML5's FileReader to save the DataUrl
(base64 string) to a hidden field
, that is posted along with the crop coordinates and dimensions, and everything else in that form
.
The essence:
base64 data, if you want to test yourself:
http://kristianbak.com/test_image.txt
- base64 string is posted to the action, and received as the parameter
imageData
- the action converts the string to a base64 byte array, like this:
byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());
EncodeTo64 extension method:
public static string EncodeTo64(this String toEncode)
{
var toEncodeAsBytes = Encoding.ASCII.GetBytes(toEncode);
var returnValue = Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
After the base64 string is converted to a byte array, I read the bytes into the memory using a MemoryStream
:
using (var imageStream = new MemoryStream(imageBytes, false))
{
Image image = Image.FromStream(imageStream); //ArgumentException: Parameter is not valid.
}
I have also tried the following variations:
a)
using (var imageStream = new MemoryStream(imageBytes))
{
Bitmap image = new Bitmap(imageStream); //ArgumentException: Parameter is not valid.
}
b)
using (var imageStream = new MemoryStream(imageBytes))
{
imageStream.Position = 0;
Image image = Image.FromStream(imageStream); //ArgumentException: Parameter is not valid.
}
c)
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap image = (Bitmap)typeConverter.ConvertFrom(imageBytes);
d)
Using this method:
private Bitmap GetBitmap(byte[] buf)
{
Int16 width = BitConverter.ToInt16(buf, 18);
Int16 height = BitConverter.ToInt16(buf, 22);
Bitmap bitmap = new Bitmap(width, height); //ArgumentException: Parameter is not valid.
int imageSize = width * height * 4;
int headerSize = BitConverter.ToInt16(buf, 10);
System.Diagnostics.Debug.Assert(imageSize == buf.Length - headerSize);
int offset = headerSize;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
bitmap.SetPixel(x, height - y - 1, Color.FromArgb(buf[offset + 3], buf[offset], buf[offset + 1], buf[offset + 2]));
offset += 4;
}
}
return bitmap;
}
Conclusion:
I feel that there's something else wrong, and I hope you can answer to this question.
Edit:
Sample of the frontend code:
<script>
$(function() {
var reader = new window.FileReader();
function readImage(file, callBack) {
reader.onload = function (e) {
var image = new Image();
image.onload = function (imageEvt) {
if (typeof callBack == "function") {
callBack(e.target.result);
}
};
image.src = e.target.result;
};
reader.readAsDataURL(file);
}
$j('#file').change(function (e) {
var file = e.target.files[0];
readImage(file, function(imageData) {
$('#imageData').val(imageData);
});
});
});
</script>
@using (Html.BeginForm("UploadImage", "Images", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<input name="PostedImage.ImageData" type="hidden" id="imageData" value="" />
@* REST OF THE HTML CODE HERE *@
<p>Choose an image:</p>
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" />
}
Sample of the Controller / Action:
[HttpPost]
public ActionResult Opret(PostedImage postedImage)
{
String imageData = PostedImage.ImageData;
byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());
using (var imageStream = new MemoryStream(imageBytes, false))
{
Image image = Image.FromStream(imageStream);
}
}
I think your problem is that you are taking a base64 string that was posted to your controller , treating it like ASCII, and then converting it to base64 again.
I think you need to change this line
byte[] imageBytes = Convert.FromBase64String(imageData.EncodeTo64());
to
byte[] imageBytes = Convert.FromBase64String(imageData);
from there your bytes should be correct and you should be able to create your image
--Edit--
I took the sample data you provided in the text document and parsed it before loading it into a Bitmap. I was able to save the image to my hard drive and was greeted by a Spartan (Go Green!!)
Give this code a try and see what happens.
Please note imageData is exactly what's exposed on http://kristianbak.com/test_image.txt. I would have provided the initialization, but it's a pretty big string and would probably break things.
string imageDataParsed = imageData.Substring( imageData.IndexOf( ',' ) + 1 );
byte[] imageBytes = Convert.FromBase64String( imageDataParsed );
using ( var imageStream = new MemoryStream( imageBytes, false ) )
{
Bitmap image = new Bitmap( imageStream );
}
这篇关于C# - Base64的字节数组映像会失败,不管我怎么努力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!