如何调整图像的大小而不模糊,或使用毕加索 [英] how to resize an image without being blurred , or with using picasso

查看:223
本文介绍了如何调整图像的大小而不模糊,或使用毕加索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提高我的code帮助。

我在做什么:有一个在主要活动,点击后按钮,用户选择图像,在此之后,图像通过一个意图另一个活动(add_image.java)通过,显示在图像视图中,之后,我将图像发送给服务器。

我的问题:1)我要的道路图像发送到第二个意图,然后将其转换成图像
的最佳途径 2)然后COM preSS它,就像我可以不失去大量的质量。 在图片大小现在是376KB。所以在我的我的应用程序生病显示多个图像,以便在这样的规模,将耗费时间和网络负载。(我用的毕加索和飞度()didnt减小尺寸。)

这是我的code:

  @覆盖
       保护无效onActivityResult(INT申请code,INT结果code,意图数据){

           super.onActivityResult(要求code,因此code,数据);

            如果(要求code == 1安培;&安培;结果code == RESULT_OK和放大器;&放大器;数据= NULL和放大器;!&安培;!data.getData()= NULL){

                //文件名
                文件路径= data.getData();
                尝试 {
                //捆绑extras2 = data.getExtras();
                    位图= MediaStore.Images.Media.getBitmap(getContentResolver(),文件路径);
                    ByteArrayOutputStream流=新ByteArrayOutputStream();
                   字节imageInByte [] = stream.toByteArray();
                  意图I =新的意图(这一点,AddImage.class);
                  i.putExtra(形象,imageInByte);
                  startActivity(ⅰ);
                }赶上(IOException异常E){
                    e.printStackTrace(); }}}
 

在这里,我收到的图片

 字节[]的字节数组= getIntent()getByteArrayExtra(图像)。
            EN codeDIMAGE = Base64.en codeToString(字节数组,Base64的);
            BMP = BitmapFactory.de codeByteArray(字节数组,0,byteArray.length);
          ImageView的ImageView的=(ImageView的)findViewById(R.id.imageView);
            imageview.setImageBitmap(BMP);
 

解决方案

试试下面的code,你可能需要修改一些参数按照您的要求:

创建MainActivity如下:

 公共类MainActivity扩展活动实现OnClickListener {
私人最终诠释REQUEST_IMAGE_GALLERY = 2000;

@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    findViewById(R.id.button).setOnClickListener(本);
}

@覆盖
公共无效的onClick(视图v){
    开关(v.getId()){
    案例R.id.button:
        pickImageFromGallery();
        打破;

    默认:
        打破;
    }
}

私人无效pickImageFromGallery(){
    意向意图=新的意图(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType(图像/ *);
    startActivityForResult(Intent.createChooser(意向,选择文件),
            REQUEST_IMAGE_GALLERY);
}

@覆盖
保护无效onActivityResult(INT申请code,INT结果code,意图数据){
    // TODO自动生成方法存根
    super.onActivityResult(要求code,因此code,数据);

    如果(结果code!= Activity.RESULT_OK){
        返回;
    }

    如果(要求code == REQUEST_IMAGE_GALLERY){
        乌里selectedImageUri = data.getData();

        的String [] filePathColumn = {MediaStore.Images.Media.DATA};
        光标光标= getContentResolver()查询(selectedImageUri,
                filePathColumn,NULL,NULL,NULL);
        cursor.moveToFirst();
        INT参数:columnIndex = cursor.getColumnIndex(filePathColumn [0]);
        字符串picturePath = cursor.getString(参数:columnIndex);
        cursor.close();

        Log.e(PATH,+ picturePath);
        意向意图=新的意图(这一点,AddImage.class);
        intent.putExtra(PATH,picturePath);
        startActivity(意向);

    }
}
}
 

现在创建activity_main.xml如下:

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
的xmlns:工具=htt​​p://schemas.android.com/tool​​s
机器人:layout_width =match_parent
机器人:layout_height =match_parent>

<按钮
    机器人:ID =@ + ID /按钮
    风格=机器人:ATTR / buttonStyleSmall
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=ChooseButton/>

    < / LinearLayout中>
 

然后,我们需要创建AddImage活动如下:

 公共类AddImage延伸活动{
@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.add_image);
    ImageView的ImageView的=(ImageView的)findViewById(R.id.image_view);
    如果(getIntent()!= NULL){
        字符串路径= getIntent()getStringExtra(PATH)。
        Log.e(PATHR,+路径);
        新BitmapWorkerTask(ImageView的).execute(路径);
    }

}

私人布尔isNeedToBeScaled(字符串路径){
    档案文件=新的文件(路径);

    如果(file.length()>(1024 * 1024)及&安培; ISEXIST(路径)){
        Log.e(SCALEIMAGE,SACLE);
        返回true;
    }
    返回false;
}

私人布尔ISEXIST(字符串路径){
    档案文件=新的文件(路径);
    返回file.exists();
}

私人位图getScaledImage(字符串路径){
    BitmapFactory.Options选项=新BitmapFactory.Options();
    options.inJustDe codeBounds = TRUE;
    BitmapFactory.de codeFILE(路径选择);

    INT srcWidth = options.outWidth;
    INT srcHeight = options.outHeight;
    INT [] newWH =新INT [2];
    newWH [0] = srcWidth / 2;
    newWH [1] =(newWH [0] * srcHeight)/ srcWidth;

    INT inSampleSize = 2;
    而(srcWidth / 2  - ; = newWH [0]){
        srcWidth / = 2;
        srcHeight / = 2;
        inSampleSize * = 2;

        options.inJustDe codeBounds = FALSE;
        options.inDither = FALSE;
        options.inSampleSize = inSampleSize;
        options.inScaled = FALSE;
        options.in preferredConfig = Bitmap.Config.RGB_565;
    }
    位图sampledSrcBitmap = BitmapFactory.de codeFILE(路径选择);

    返回sampledSrcBitmap;
}

类BitmapWorkerTask扩展的AsyncTask<字符串,太虚,位图> {
    私人最终的WeakReference< ImageView的> imageViewReference;

    公共BitmapWorkerTask(ImageView的mImageView){
        imageViewReference =新的WeakReference< ImageView的>(mImageView);
    }

    @覆盖
    受保护的位图doInBackground(字符串... PARAMS){
        位图缩放= NULL;
        如果(isNeedToBeScaled(PARAMS [0])){
            位图D组;

            D = getScaledImage(PARAMS [0]);
            INT NH =(int)的(d.getHeight()*(512.0 / d.getWidth()));
            缩放= Bitmap.createScaledBitmap(D,512,NH,真正的);

        } 其他 {
            缩放= BitmapFactory.de codeFILE(PARAMS [0],NULL);
        }
        返回比例;

    }

    @覆盖
    保护无效onPostExecute(位图的结果){

        如果(imageViewReference = NULL和放大器;!&安培;!结果= NULL){
            最后的ImageView ImageView的= imageViewReference.get();
            如果(ImageView的!= NULL){
                imageView.setImageBitmap(结果);
                imageView.setVisibility(View.VISIBLE);

            }
        }
    }

}
}
 

I need help in improving my code .

What I am doing : There is a button in main activity, when clicked , user choose the image , after that, the image is passed through an intent to another activity(add_image.java) and displayed in an image view , after that I send the image to the server.

My problems:1) I want the best way to send the path image to second intent then convert it into image
2) then compress it as much as I can without loosing a lot of its quality. the image size now is 376kb . so in my my app Ill displaying several images so in such size it will consume time and internet to load.( I am using picasso and fit() didnt decrease the size.)

here is my code :

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

           super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {

                //file name
                filePath = data.getData();
                try {
                //  Bundle extras2 = data.getExtras();
                    bitmap  = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();               
                   byte imageInByte[] = stream.toByteArray();                    
                  Intent i = new Intent(this, AddImage.class);
                  i.putExtra("image", imageInByte);
                  startActivity(i);
                } catch (IOException e) {
                    e.printStackTrace();     }   }   }    

And here I am receiving the image

     byte[] byteArray = getIntent().getByteArrayExtra("image");
            encodedImage = Base64.encodeToString(byteArray, Base64);
            bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
          ImageView imageview = (ImageView) findViewById(R.id.imageView);
            imageview.setImageBitmap(bmp);

解决方案

Try following code, you might need to modify some of the parameters as per your requirement :

Create MainActivity as following :

public class MainActivity extends Activity implements OnClickListener {
private final int REQUEST_IMAGE_GALLERY = 2000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViewById(R.id.button).setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button:
        pickImageFromGallery();
        break;

    default:
        break;
    }
}

private void pickImageFromGallery() {
    Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(Intent.createChooser(intent, "Select File"),
            REQUEST_IMAGE_GALLERY);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) {
        return;
    }

    if (requestCode == REQUEST_IMAGE_GALLERY) {
        Uri selectedImageUri = data.getData();

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImageUri,
                filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        Log.e("PATH", "" + picturePath);
        Intent intent = new Intent(this, AddImage.class);
        intent.putExtra("PATH", picturePath);
        startActivity(intent);

    }
}
}

Now create activity_main.xml as follows :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
    android:id="@+id/button"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="ChooseButton" />

    </LinearLayout>

Then we need to create AddImage activity as follows :

public class AddImage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_image);
    ImageView imageView = (ImageView) findViewById(R.id.image_view);
    if (getIntent() != null) {
        String path = getIntent().getStringExtra("PATH");
        Log.e("PATHR", "" + path);
        new BitmapWorkerTask(imageView).execute(path);
    }

}

private boolean isNeedToBeScaled(String path) {
    File file = new File(path);

    if (file.length() > (1024 * 1024) && isExist(path)) {
        Log.e("SCALEIMAGE", "SACLE");
        return true;
    }
    return false;
}

private boolean isExist(String path) {
    File file = new File(path);
    return file.exists();
}

private Bitmap getScaledImage(String path) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    int srcWidth = options.outWidth;
    int srcHeight = options.outHeight;
    int[] newWH = new int[2];
    newWH[0] = srcWidth / 2;
    newWH[1] = (newWH[0] * srcHeight) / srcWidth;

    int inSampleSize = 2;
    while (srcWidth / 2 >= newWH[0]) {
        srcWidth /= 2;
        srcHeight /= 2;
        inSampleSize *= 2;

        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inSampleSize = inSampleSize;
        options.inScaled = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
    }
    Bitmap sampledSrcBitmap = BitmapFactory.decodeFile(path, options);

    return sampledSrcBitmap;
}

class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;

    public BitmapWorkerTask(ImageView mImageView) {
        imageViewReference = new WeakReference<ImageView>(mImageView);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap scaled = null;
        if (isNeedToBeScaled(params[0])) {
            Bitmap d;

            d = getScaledImage(params[0]);
            int nh = (int) (d.getHeight() * (512.0 / d.getWidth()));
            scaled = Bitmap.createScaledBitmap(d, 512, nh, true);

        } else {
            scaled = BitmapFactory.decodeFile(params[0], null);
        }
        return scaled;

    }

    @Override
    protected void onPostExecute(Bitmap result) {

        if (imageViewReference != null && result != null) {
            final ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(result);
                imageView.setVisibility(View.VISIBLE);

            }
        }
    }

}
}

这篇关于如何调整图像的大小而不模糊,或使用毕加索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆