0

好的,这就是我所拥有的:

几行代码,可以选择/拍摄照片并将其上传到我的服务器:

System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
        bmp.SetSource(e.ChosenPhoto);
        image1.Source = bmp;
        BitmapImage bitmapImage = bmp;
        var largest = Math.Max(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
        var ratio = largest / 1024;
        var width = bitmapImage.PixelWidth / ratio;
        var height = bitmapImage.PixelHeight / ratio;
        WriteableBitmap wb = new WriteableBitmap(bitmapImage);
        Stream str = null; 
        wb.SaveJpeg(str, width, height, 0, 75);

        byte[] sbytedata = ReadToEnd(str);
        string s = EncodeTo64(sbytedata.ToString());
        WebClient wc = new WebClient();
        Uri u = new Uri("//something ;)//");
        wc.OpenWriteCompleted+=new OpenWriteCompletedEventHandler(wc_OpenWriteCompleted);
        wc.OpenWriteAsync(u, "POST", sbytedata);

而且..它不起作用:异常 - 屏幕

此外,您还需要 ReadToEnd() 函数。这是:

    public static byte[] ReadToEnd(System.IO.Stream stream)
{
    long originalPosition = stream.Position;
    stream.Position = 0;

    try
    {
        byte[] readBuffer = new byte[4096];

        int totalBytesRead = 0;
        int bytesRead;

        while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
        {
            totalBytesRead += bytesRead;

            if (totalBytesRead == readBuffer.Length)
            {
                int nextByte = stream.ReadByte();
                if (nextByte != -1)
                {
                    byte[] temp = new byte[readBuffer.Length * 2];
                    Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                    Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                    readBuffer = temp;
                    totalBytesRead++;
                }
            }
        }

        byte[] buffer = readBuffer;
        if (readBuffer.Length != totalBytesRead)
        {
            buffer = new byte[totalBytesRead];
            Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
        }
        return buffer;
    }
    finally
    {
        stream.Position = originalPosition;
    }
}

有任何想法吗?

4

2 回答 2

0

改变

Stream str = null; 

至:

Stream str = new MemoryStream();

请记住 - 调试器会将下一条语句显示为导致异常的语句之后的语句。所以你实际上是在你看到的那个声明之前死去的。

于 2012-04-18T17:24:29.097 回答
0

好吧,这似乎Stream str = null;是错误的,您需要对其进行实例化,即 SaveToJpeg 写入现有流而不是创建一个并写入它。

于 2012-04-18T17:28:46.023 回答