gpt4 book ai didi

c# - Android通过tcp压缩并发送图像

转载 作者:行者123 更新时间:2023-12-01 14:58:01 25 4
gpt4 key购买 nike

我正在尝试从相机捕获预览图像,然后通过 WiFi 将其发送到我的计算机。

流程如下:

在我的手机上:启动相机预览,然后压缩并通过 TCP 连接发送。在我的计算机上:接收压缩数据并保存照片。

我在移动设备上使用此代码:

try {           
ByteArrayOutputStream outstr = new ByteArrayOutputStream();

Camera.Parameters parameters = camera.getParameters();
Size size = parameters.getPreviewSize();
YuvImage image = new YuvImage(data, parameters.getPreviewFormat(), size.width, size.height, null);
image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), 100, outstr);

out.writeBytes("DATA|" + outstr.size() + "\n");
out.flush();
out.write(outstr.toByteArray());
out.flush();

} catch (IOException e) {
t.append("ER: " + e.getMessage());
}

onCreate方法中创建的DataOutputStream在哪里:

tcp = new Socket("192.168.0.12", 6996);         
in = new BufferedReader(new InputStreamReader(tcp.getInputStream()));
out = new DataOutputStream(tcp.getOutputStream());

然后在我的计算机上使用此代码:

    StreamReader sr = new StreamReader(client.GetStream());
string line = sr.ReadLine();

if(line.StartsWith("DATA"))
{
piccount++;
int size = Convert.ToInt32(line.Substring(5));
Console.WriteLine("PHOTO, SIZE: " + size + ", #: " + piccount);
byte[] data = new byte[size];

client.GetStream().Read(data, 0, size);

FileStream fs = System.IO.File.Create("C:/Users/M/photo"+piccount+".jpeg");
fs.Write(data, 0, data.Length);
fs.Flush();
fs.Close();
}

问题是,有些传输的图片正常,但有些已损坏。问题可能出在哪里?

最佳答案

问题出在这一行 client.GetStream().Read(data, 0, size);Stream.Read 不能确保它会准确读取 size 字节。您应该检查其返回值并继续读取,直到读取所有字节。

http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx

Return Value

The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

如果您打算读取整个流,您可以使用以下代码:

using (FileStream fs = System.IO.File.Create("C:/Users/M/photo" + piccount + ".jpeg"))
{
client.GetStream().CopyTo(fs);
}

关于c# - Android通过tcp压缩并发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14091094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com