mysql中表mtable中有两个字段id (int),photo (blob);python中如何把2个图片,存到mtable中为id=1的同一条记录中photo的字段中;并且在android中能读取出来,请给出代码
时间: 2024-05-11 20:13:58 浏览: 144
mysql 将图片以二进制格式存储到数据库,并从数据库读取图片显示
Python代码:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 读取图片文件
with open("image1.jpg", "rb") as f:
photo1 = f.read()
with open("image2.jpg", "rb") as f:
photo2 = f.read()
# 将两张图片存入数据库
mycursor = mydb.cursor()
mycursor.execute("UPDATE mtable SET photo = %s WHERE id = 1", (photo1,))
mycursor.execute("UPDATE mtable SET photo = %s WHERE id = 1", (photo2,))
mydb.commit()
```
Android代码:
```java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
// 从数据库中读取图片并显示
new LoadImageTask().execute("http://localhost:8000/get_image.php?id=1");
}
private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
String imageUrl = urls[0];
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
```
注:Android端的图片加载使用了AsyncTask异步任务,需要注意在Android 11及以上版本中,需要在AndroidManifest.xml中添加以下权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
阅读全文