繁体   English   中英

图片到base64然后上传

[英]Image to base64 then upload

我正在使用Xamarin.Forms PCL应用程序,用户可以在其中选择照片并上传。 我想将所选照片发送到网络服务,以便可以检查其正确格式和文件大小,然后将其上传到Google照片。

要将其传输到我的Web服务,它需要是一个字符串。 我尝试使用

MediaFile file;

var stream = file.GetStream();
var bytes = new byte[stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string content = System.Convert.ToBase64String(bytes);

我的第一个问题是我不知道将文件初始化为什么,以使其正确转换。 一旦用户选择了一个图像,图像将通过ImageSource image_source;存储在内存中ImageSource image_source;

一旦上传,它就可以到达我的PHP网站,并且我得到的图像带有$image = $_POST['image_string'];

我的第二个问题是如何将其转换回图像以检查文件类型和图像大小?

它通过以下方式发送到网站

var values = new Dictionary<string, string>
        {
            {"session", UserData.session },
            {"image", ImageAsBase64().Result.Length.ToString() }
        };

        var content = new FormUrlEncodedContent(values);
        var response = await App.client.PostAsync(WebUtils.URL, content);
        var responseString = await response.Content.ReadAsStringAsync();
        string page_result = responseString;

您可以使用PHP的GD图像库基本上完成图像所需的任何操作。

要从字符串获取图像,请使用以下命令:

 $sourceImg = imagecreatefromstring(file_get_contents($file));

然后保存图像:

 imagejpeg($sourceImg, $targetPath, 60);  //60 is a compression

以下是一些链接:

imagecreatefromstring():

http://php.net/manual/en/function.imagecreatefromstring.php

GD库: http//php.net/manual/zh/book.image.php

将图像上载到服务器并没有意义,而不是检查其大小。 除非您要压缩它并减小服务器上的大小。

这是检查图像尺寸的方法:

var ImageStream = file.GetStream();
var bytes = new byte[ImageStream.Length];
//check if image is too big
double ImageSizeInMB = ((double)(bytes.Length) / (1024 * 1024));
//check if image size is bigger than 5 MB
if(ImageSizeInMB > 5)
{
    await DisplayAlert("Error", "Image is too big,reduce resolution and try again", "OK");
    return;
}

之后,您需要要求用户重新拍摄图片,或者可以开始对其进行压缩并调整其大小。 拍摄后我无法压缩图像,但是我确信这是可能的,因为您可以在使用媒体插件选项拍摄图像之前进行压缩。

现在将图像转换为base64:

await ImageStream.ReadAsync(bytes, 0, (int)ImageStream.Length);
string base64 = System.Convert.ToBase64String(bytes);

就是这样,您现在有了相机拍摄的图像并将其转换为Base64字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM