编码和解码- JPG到base64

本文关键字:base64 JPG 解码 编码 | 更新日期: 2023-09-27 18:05:02

我正在开发一个Windows Phone应用程序,该应用程序使用PHP将用户选择的照片上传到服务器。为此,我试图将图像转换为base64,并将其POST到PHP,在那里它被解码回JPG图像。

base64字符串成功地发布到PHP,但我总是在服务器上得到一个损坏的JPG文件,而不是原始图像(这意味着在编码/解码图像时存在一些错误)。

Application的c#代码是:

public partial class SamplePage : PhoneApplicationPage
    {
        public SamplePage()
        {
            InitializeComponent();
        }
        PhotoChooserTask selectphoto = null;
        private void SampleBtn_Click(object sender, RoutedEventArgs e)
        {
            selectphoto = new PhotoChooserTask();
            selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
            selectphoto.Show();
        }
        void selectphoto_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BinaryReader reader = new BinaryReader(e.ChosenPhoto);
                image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
                txtBX.Text = e.OriginalFileName;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://"+QR_Reader.MainPage.txtBlck+"/beamer/saveimage.php");
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                Stream photoStream = ImageToStream(image1);
                BitmapImage bimg = new BitmapImage();
                bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
                byte[] bytearray = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    WriteableBitmap wbitmp = new WriteableBitmap(bimg);
                    wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
                    ms.Seek(0, SeekOrigin.Begin);
                    bytearray = ms.GetBuffer();
                }
                string str = Convert.ToBase64String(bytearray);
                string postData = String.Format("image={0}", str);   
                // Getting the request stream.
                request.BeginGetRequestStream
                (result =>
                {
                    // Sending the request.
                    using (var requestStream = request.EndGetRequestStream(result))
                    {
                        using (StreamWriter writer = new StreamWriter(requestStream))
                        {
                            writer.Write(postData);
                            writer.Flush();
                        }
                    }
                    // Getting the response.
                    request.BeginGetResponse(responseResult =>
                    {
                        var webResponse = request.EndGetResponse(responseResult);
                        using (var responseStream = webResponse.GetResponseStream())
                        {
                            using (var streamReader = new StreamReader(responseStream))
                            {
                                string srresult = streamReader.ReadToEnd();
                            }
                        }
                    }, null);
                }, null);
            }  // end of taskresult == OK           
        }  // end of select photo completed
        private Stream ImageToStream(Image image1)
        {
            WriteableBitmap wb = new WriteableBitmap(400, 400);
            wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
            wb.Invalidate();
            Stream myStream = new MemoryStream();
            wb.SaveJpeg(myStream, 400, 400, 0, 70);
            return myStream;
        }
    }  // End of Class

服务器端用于解码和保存图像的PHP代码为:

<?php
function base64_to_image( $imageData, $outputfile ) {
    // encode & write data (binary)
    $ifp = fopen( $outputfile, "wb" );
    fwrite( $ifp, base64_decode( $imageData ) );
    fclose( $ifp );
    // return output filename 
    return( $outputfile );
}       
if (isset($_POST['image'])) {
    base64_to_image($_POST['image'], "img.jpg");
}
else
    die("no image data found");
?>

我不知道这是怎么回事。我已经找了几个小时来做这件事,但还是失败了。

请帮帮我。

编辑:

我刚刚发现,我总是得到相同的base64字符串,无论我选择任何图像。这是base64转换后得到的结果:http://textuploader.com/?p=6& id = vWZy

我现在真的很困惑。每个图像都得到相同的输出。我不知道为什么会这样。

我真的很想这样做,我被困在这里,在base64编码。

编码和解码- JPG到base64

这可能不是所有的问题,但这段代码被打破了:

byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
    WriteableBitmap wbitmp = new WriteableBitmap(bimg);
    wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
    ms.Seek(0, SeekOrigin.Begin);
    bytearray = ms.GetBuffer();
}

通过使用GetBuffer,您将获得底层缓冲区,它可能比实际数据大。您可以使用ToArray代替-并且在使用GetBufferToArray之前不需要"倒带"流:

byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
    WriteableBitmap wbitmp = new WriteableBitmap(bimg);
    wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
    bytearray = ms.ToArray();
}

如果这不起作用,您应该仔细查看前后文件,最好是在二进制文件编辑器中:

  • 它们的尺寸一样吗?
  • 它们在哪里不同,如何不同?有什么规律吗?