【发布时间】:2022-01-04 23:03:14
【问题描述】:
我的 android 应用程序和台式电脑之间有一个 TCP 连接,我想通过套接字发送 ImageView。我的问题是图像显然已成功发送,因为它有 9.7KiB。但是,当我尝试可视化此图像时,我得到一个黑色图像,并且在 Android Studio IDE 中没有抛出明显的错误。
发送图片的安卓应用:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.frame_image);
private final OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_camera:
if (!Check.isFastClick()) {
return;
}
if (mCameraHandler != null) {
if (mCameraHandler.isOpened()) {
if (checkPermissionWriteExternalStorage()) {
Drawable drawable = mImageView.getDrawable();
Bitmap bitmap = getBitmapFromDrawable(drawable);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
byte[] array = baos.toByteArray();
SendImageClient sendImageClient = new SendImageClient();
sendImageClient.execute(array);
}
}
}
break;
};
public Bitmap getBitmapFromDrawable(Drawable drawable){
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
drawable.draw(canvas);
return bitmap;
}
public class SendImageClient extends AsyncTask<byte[], Void, Void> {
@Override
protected Void doInBackground(byte[]... voids) {
try {
Socket socket= new Socket("192.168.0.14",9999);
OutputStream out = socket.getOutputStream();
DataOutputStream dataOutputStream= new DataOutputStream(out);
dataOutputStream.write(voids[0],0,voids[0].length);
dataOutputStream.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
activity_main.xml
<com.serenegiant.widget.UVCCameraTextureView
android:id="@+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/menu_layout" />
<com.serenegiant.widget.AutoFitTextureView
android:id="@+id/textureView"
android:layout_width="480px"
android:visibility="invisible"
android:layout_toRightOf="@id/menu_layout"
android:layout_height="640px" />
<ImageView
android:id="@+id/frame_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/camera_view"
android:layout_alignLeft="@id/camera_view"
android:layout_alignRight="@id/camera_view"
android:layout_alignTop="@id/camera_view" />
服务器脚本.py
from socket import *
port = 9999
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1)
conn, addr = s.accept()
print("Connected by the ",addr)
with open('/home/pi/Desktop/frames_saved/image.jpg', 'wb') as file:
while True:
data = conn.recv(1024*8)
if not data: break
file.write(data)
conn.close()
为什么我得到一个黑色的图像,我如何才能将 ImageView 中显示的实际图像发送到桌面?
【问题讨论】:
标签: python java android image sockets