将图像从Firebase转换为灰度并在ImageView中显示它

时间:2018-04-13 07:52:10

标签: android firebase bitmap firebase-storage

OnActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // When an Image is picked
    if (requestCode == RESULT_LOAD && resultCode == RESULT_OK) {
        Uri resultUri = data.getData();

        CropImage.activity(resultUri)
                .start(this);
    }

    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        progress.setMessage("Uploading");
        progress.show();

        Uri uri = result.getUri();
        StorageReference path = storage.child("Raw").child(Uid + ".jpg");
        path.putFile(uri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                if (task.isSuccessful()) {

                    loadUserInformation();

                    downloadUrl  = task.getResult().getDownloadUrl().toString();

                    mdatabase.child("Image").setValue(downloadUrl).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            progress.dismiss();
                            Toast.makeText(SetUpProfileDisplayPicture.this, "Succesfully Uploaded", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    Toast.makeText(SetUpProfileDisplayPicture.this, "Error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

更新个人资料照片

private void updateDisplayPicture() {
    HashMap<String, Object> userMap = new HashMap<>();
    userMap.put("Image", downloadUrl);
    userMap.put("Thumb_image", "Default");

    mdatabase.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            if (task.isSuccessful()) {
                Toast.makeText(getApplicationContext(), "Profile Successfully Updated", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(SetUpProfileDisplayPicture.this, HomeScreen.class));
                finish();
            }
        }
    });
}

的UserInfo

public void loadUserInformation() {
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference usesrRef = rootRef.child("Users").child(Uid);
    final ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ImageView profilePic = (ImageView) findViewById(R.id.imageView);
            TextView Name = (TextView) findViewById(R.id.name);
            TextView Status = (TextView) findViewById(R.id.status);
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                String name = dataSnapshot.child("Name").getValue().toString();
                String status = dataSnapshot.child("Status").getValue().toString();
                String image = dataSnapshot.child("Image").getValue().toString();

                Name.setText(name);
                Status.setText(status);

                Name.setVisibility(View.VISIBLE);
                Status.setVisibility(View.VISIBLE);

                Picasso.get().load(image).into(profilePic);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getApplicationContext(), "Error Loading UserDetails", Toast.LENGTH_LONG).show();
        }
    };
    usesrRef.addListenerForSingleValueEvent(eventListener);
}

我在Stack Overflow中看到过这样的问题,但我无法理解答案或得到结果。第一个用户上传图像,然后进入firebase,然后我获取它。如何在imageView中显示之前将其变为略微或完全黑白?

ERROR

FATAL EXCEPTION: main
        Process: com.appmaster.akash.messageplus, PID: 9894
        android.os.NetworkOnMainThreadException
           at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
           at com.android.org.conscrypt.OpenSSLSocketImpl$SSLOutputStream.write(OpenSSLSocketImpl.java:755)
           at com.android.okhttp.okio.Okio$1.write(Okio.java:76)
           at com.android.okhttp.okio.AsyncTimeout$1.write(AsyncTimeout.java:155)
           at com.android.okhttp.okio.RealBufferedSink.flush(RealBufferedSink.java:221)
           at com.android.okhttp.internal.http.HttpConnection.flush(HttpConnection.java:141)
           at com.android.okhttp.internal.http.HttpTransport.finishRequest(HttpTransport.java:52)
           at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:903)
           at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:789)
           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:443)
           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
           at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
           at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
           at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
           at com.appmaster.akash.messageplus.SetUpProfileDisplayPicture$6.onDataChange(SetUpProfileDisplayPicture.java:225)
           at com.google.firebase.database.zzp.onDataChange(Unknown Source)
           at com.google.android.gms.internal.zzduz.zza(Unknown Source)
           at com.google.android.gms.internal.zzdwu.zzbvb(Unknown Source)
           at com.google.android.gms.internal.zzdxa.run(Unknown Source)
           at android.os.Handler.handleCallback(Handler.java:742)
           at android.os.Handler.dispatchMessage(Handler.java:95)
           at android.os.Looper.loop(Looper.java:157)
           at android.app.ActivityThread.main(ActivityThread.java:5571)
           at java.lang.reflect.Method.invoke(Native Method)
           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)

1 个答案:

答案 0 :(得分:2)

首先将图片网址转换为位图。然后调用一个方法将Bitmap转换为灰度:

    public void loadUserInformation() {
    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
    final DatabaseReference usesrRef = rootRef.child("Users").child(Uid);
    final ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ImageView profilePic = (ImageView) findViewById(R.id.imageView);
            TextView Name = (TextView) findViewById(R.id.name);
            TextView Status = (TextView) findViewById(R.id.status);
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                String name = dataSnapshot.child("Name").getValue().toString();
                String status = dataSnapshot.child("Status").getValue().toString();
                String image = dataSnapshot.child("Image").getValue().toString();
Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
                    URL url = new URL(image);
                    HttpURLConnection connection = (HttpURLConnection) 
                    url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    Bitmap myBitmap =BitmapFactory.decodeStream(input);
                    toGrayscale(myBitmap,profilePic)
                 } catch (Exception e) {
                  e.printStackTrace();
                 }
             }
          });

                thread.start(); 


                Name.setText(name);
                Status.setText(status);

                Name.setVisibility(View.VISIBLE);
                Status.setVisibility(View.VISIBLE);

                //Picasso.get().load(image).into(profilePic);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(getApplicationContext(), "Error Loading UserDetails", Toast.LENGTH_LONG).show();
        }
    };
    usesrRef.addListenerForSingleValueEvent(eventListener);
}


public void toGrayscale(Bitmap bmpOriginal,ImageView profilePic)
       {
         profilePic.setImageBitmap(bmpOriginal);
         // Apply grayscale filter
         ColorMatrix matrix = new ColorMatrix();
         matrix.setSaturation(0);
         ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
         profilePic.setColorFilter(filter);

        }

回答学分:

https://stackoverflow.com/a/11831325
https://stackoverflow.com/a/3391061