簡體   English   中英

RxJava將字節數組轉換為位圖

[英]RxJava convert byte array to Bitmap

對不起我的英語不好。 現在,我學習rxJava 1並嘗試將byte []轉換為Bitmap並將其設置為imageview。 但是它工作緩慢。 我使用rxJava正確嗎? ps:我檢查和asynkTask的工作比rxJava更好,這怎么可能?

Observable.just(data)
                .map(new Func1<byte[], Bitmap>() {
                    @Override
                    public Bitmap call(byte[] bytes) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = false;
                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                        options.inDither = true;
                        options.inMutable = true;

                        Bitmap largeBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                        Bitmap bitmap = Bitmap.createScaledBitmap(largeBitmap
                                , (int) ((float) largeBitmap.getWidth() / 10)
                                , (int) ((float) largeBitmap.getHeight() / 10)
                                , true);

                        if (bitmap.getWidth() > bitmap.getHeight()) {
                            Matrix matrix = new Matrix();
                            matrix.postRotate(90); // anti-clockwise by 90 degrees

                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                        }

                        float k = (float) bitmap.getWidth() / (float) w_target;

                        if (w_target < bitmap.getWidth()) {
                            bitmap = Bitmap.createScaledBitmap(bitmap, w_target, (int) ((float) bitmap.getHeight() / k), true);
                        }

                        return createBlackAndWhite(bitmap);
                    }
                })
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Bitmap>() {
                    @Override
                    public void call(Bitmap bitmap) {
                        imageview.setImageBitmap(bitmap);
                    }
                }); 

也許您應該更改用於處理該過程的Schedulers.io() ,而不是Schedulers.computation()至少對某些計算嘗試使用Schedulers.computation()

根據文檔

Calculation() :創建並返回用於計算工作的Scheduler。 這可以用於事件循環,處理回調和其他計算工作。 不要在此調度程序上執行IO綁定工作。 請改用Schedulers.io()。

io() :創建並返回用於IO綁定工作的Scheduler。 該實現由Executor線程池支持,該線程池將根據需要增長。 這可用於異步執行阻塞IO。 不要在此調度程序上執行計算工作。 請改用Schedulers.computation()。

希望這可以幫助。

對不起我的英語不好。

將調度程序反轉為

.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())

您觀察到的線程是其中將調用imageView.setBitmap()的線程,另一方面,subscriptionOn將設置用於位圖操作的線程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM