gpt4 book ai didi

java - 如何以 kb 为单位获取位图的大小

转载 作者:行者123 更新时间:2023-11-30 04:53:55 27 4
gpt4 key购买 nike

我正在尝试在 firebase 存储中上传图像,我希望图像不应大于 50 kb 我正在尝试获取位图的大小,以便我可以知道位图的大小是否超过 50 kb这图片不会显示在画廊中 我已经尝试了许多人建议的代码,但没有一个对我有用。请帮我解决这个问题。这是我的代码:

@Override
protected void onActivityResult( int requestCode , int resultCode , @Nullable Intent data )

{
super.onActivityResult (requestCode , resultCode , data);
if(requestCode == ChooseImage && resultCode == RESULT_OK && data != null && data.getData() != null){

userProfileImage = data.getData ();

try {

Bitmap bitmap=MediaStore.Images.Media.getBitmap (getContentResolver ( ) , userProfileImage);

if (bitmap.getHeight () * bitmap.getRowBytes () < 50000)
profile_photo.setImageBitmap (bitmap);
btn.setOnClickListener (new View.OnClickListener ( ) {
@Override
public void onClick( View v ) {
uploaImage ();
}
});


} catch (IOException e) {
e.printStackTrace ( );
Toast.makeText (this , e.getMessage () , Toast.LENGTH_SHORT).show ( );
}
}
}

最佳答案

试试这段代码:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if (requestCode == ChooseImage && resultCode == RESULT_OK && data != null && data.getData() != null) {
userProfileImage = data.getData();
try {

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), userProfileImage);
if (bitmap.getHeight() * bitmap.getRowBytes() < 50000)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long bitmap_size = imageInByte.length / 1024;
profile_photo.setImageBitmap(bitmap);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploaImage();
}
});


} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}

长变量 bitmap_size 将为您提供以 KB 为单位的图像大小

关于java - 如何以 kb 为单位获取位图的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550336/

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