[英]Send image to server from gallery android bitmap
我試圖從圖庫向服務器發送圖像,並使用Base64
對其進行了壓縮。
我開始了一個畫廊活動:
private void startGalleryActivity() {
Intent intent = new Intent();
intent.setType("image/*");
String selectPicture = getResources().getString(R.string.select_picture);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, GALLERY);
}
我在onActivityResult
收到了結果:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY && resultCode == MainActivity.RESULT_OK) {
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
imageView.setImageBitmap(BitmapFactory.decodeFile(imagePath));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeFile(imagePath, options);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Server s = new Server("new");
s.send(encoded);
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
當我發送圖片進行投放時,其尺寸要高出4倍。 如果我在讀取圖像后將其寫入,則將以兩倍大小寫入。 為什么我有這個開銷?
為什么我有這個開銷?
除了Base64開銷本身之外,您還將圖像重新編碼為PNG。 如果圖像以JPEG之類的其他形式開始,則該圖像的PNG版本可能會更大。
另外,請刪除前面的四行, // Let's read picked image path using content resolver
。 首先,該代碼將在數億個Android設備上失敗,因為Uri
不是file ,並且您不能假定可以獲取該數據的本地文件系統路徑。 其次,您不需要它,因為BitmapFactory
具有可與getContentResolver().openInputStream(pickedImage)
一起使用的decodeStream()
方法。
另外,請不要在BitmapFactory
兩次調用decode...()
。 一次加載位圖。 將位圖用於ImageView
和上載。
在PNG上調用compress不會使您的文件變小,因為它已經被壓縮。 將二進制文件轉換為文本流確實會使它變大。 為了避免通過將PNG文件轉換為文本文件而減少開銷,只需按原樣以字節數組形式發送文件即可。 並在標題中添加文件長度。 您可以使用DataOutputStream來執行此操作。
byte[] byteArray = byteArrayOutputStream .toByteArray();
ByteArrayOutputStream btOS = new ByteArrayOutputStream();
DataOutputStream dataOS = new DataOutputStreamEx(btOS);
dataOS.writeInt(byteArray.length); // length of file
dataOS.write(byteArray); // actual file
dataOS.write(0); // end of field
dataOS.close()
我不知道您在后端使用的是什么,但您只能讀取將收到的內容的前4個字節,這就是文件的長度。 並使用該長度讀取整個文件。
您正在使用Bitmap和BitmapFactory將較小的jpg文件轉換為較大的png文件。 為什么不直接發送jpg? 因此,請勿首先使用Bitmap和BitmapFactory。 您最終得到的不是您的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.