图像调整大小 - 值不能为空

时间:2012-04-18 17:16:31

标签: c# visual-studio silverlight windows-phone

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

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

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);

并且..它不起作用:exception - screen

另外,你需要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;
    }
}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

更改

Stream str = null; 

要:

Stream str = new MemoryStream();

请记住 - 调试器会将下一个语句显示为引发异常的语句之后的语句。所以你实际上在你看到之前的声明上已经死了。

答案 1 :(得分:0)

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