Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/203.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从SD存储器到ByteArray的映像_Java_Android_Arrays - Fatal编程技术网

Java 从SD存储器到ByteArray的映像

Java 从SD存储器到ByteArray的映像,java,android,arrays,Java,Android,Arrays,编辑:我不知道如何将一个图像文件(example.jpg)转换成byteArray。我试图理解它是如何完成的,但到目前为止我什么都没有,我尝试了在这个网站上找到的不同方法,但似乎对我来说没有任何效果。 我在这里提出了问题,这样我就可以理解在其他人的帮助下是如何做到的 我的SD卡中有一个图像文件,我知道我的路径,现在我想获取该图像并将其转换为byteArray,我在logcat中得到了错误的结果,我想我是这样做的。我不确定输出应该是怎样的 import android.content.Intent

编辑:我不知道如何将一个图像文件(example.jpg)转换成byteArray。我试图理解它是如何完成的,但到目前为止我什么都没有,我尝试了在这个网站上找到的不同方法,但似乎对我来说没有任何效果。 我在这里提出了问题,这样我就可以理解在其他人的帮助下是如何做到的

我的SD卡中有一个图像文件,我知道我的路径,现在我想获取该图像并将其转换为byteArray,我在logcat中得到了错误的结果,我想我是这样做的。我不确定输出应该是怎样的

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.awareness.snapshot.internal.Snapshot;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
import com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;
import java.util.Map;

import static android.R.attr.bitmap;
import static android.R.attr.duration;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    public byte[] B;
    private GoogleMap mMap;
    GPSTracker gps;
    public File imageFile ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }


    /**
     Create the map when the map is ready OnMapReady, The object GPS is ccalled (GPSTraccker) to obtain
     Values for lat and long.
     */
    final Handler handler = new Handler();

    @Override
    public void onMapReady(final GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        gps = new GPSTracker(MapsActivity.this);
        double latitude = gps.getLatitude();
        double longitude = gps.getLongitude();
        LatLng sydney = new LatLng(latitude, longitude);
        //adding an automated marker to mark the users spot on the map.
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Cyprus"));

        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(19.0f));
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
          //When the map is clicked the following will occure

            @Override
            public void onMapClick(LatLng point) {
                //create a new marker on the new lat/long of the spot clicked
                MarkerOptions marker = new MarkerOptions().position(
                        new LatLng(point.latitude, point.longitude)).title("New Marker");
                //places the marker
                mMap.addMarker(marker);
                //create an object of Bitmap
                Bitmap bitmap;
                //Creating and calling object Snapshot
                SnapshotReadyCallback callback = new SnapshotReadyCallback() {
                    @Override
                    //when the snapshot is ready do the following
                    public void onSnapshotReady(Bitmap bitmap) {
                    //Creating object Date and storing it to now
                        Date now = new Date();
                        //Retribing exact date and storing it to now
                        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);


                        try {
                            //dissabling strick mode for testing , remember to remvoe this code
                            StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
                            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
                                    .permitDiskWrites()
                                    .build());

                            //mpath = /sd/date.jpg creating a dir for the image to be snaped
                            String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
                           //Calling object File.
                            File imageFile = new File(mPath);
                            FileOutputStream out = new FileOutputStream(imageFile);
                            //outputing streaming to /imagefile
                            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);

                            Log.d("Var:OUT: ", " " + out);
                            Log.d("ImageFile" ,""+ imageFile) ;
                            Log.d("mPath" ,""+ mPath) ;
                            //decompose image
                            Bitmap bmp = BitmapFactory.decodeFile(mPath);

                            ByteArrayOutputStream stream = new ByteArrayOutputStream();

                            StrictMode.setThreadPolicy(old);
                            ByteArrayOutputStream streams = new ByteArrayOutputStream();
                            bmp.compress(Bitmap.CompressFormat.PNG, 100, streams);


                            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
                            byte[] image=stream.toByteArray();
                            System.out.println("byte array:"+image);
                            Log.d("array", image.toString());
                            String img_str = Base64.encodeToString(image, 0);
                            Log.d("array_Str",img_str);
                            System.out.println("string:"+img_str);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };

                mMap.snapshot(callback);


                System.out.println(point.latitude + "---" + point.longitude);


            }
        });

    }

  //  public byte[] getBytesFromBitmap(Bitmap bitmap) {
  //      ByteArrayOutputStream stream = new ByteArrayOutputStream();
  //      bitmap.compress(Bitmap.CompressFormat.JPEG, 90, now);
  ////      Log.d("ARRAY", "" + now.toByteArray());
  //    byte[]  B = stream.toByteArray();

   //     return stream.toByteArray();

//}





    public void onSnapshotReady (Bitmap bitmap) {
        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
        Log.d("DOulefko","test");
        try {
            // image naming and path  to include sd card  appending name you choose for file
            String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

            // create bitmap screen capture
            View v1 = getWindow().getDecorView().getRootView();

            v1.setDrawingCacheEnabled(true);
        bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            File imageFile = new File(mPath);

            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();

        } catch (Throwable e) {
            // Several error may come out with file handling or OOM
            e.printStackTrace();
        }
    }
    private void openScreenshot(File imageFile) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(imageFile);
        intent.setDataAndType(uri, "image/*");
        startActivity(intent);
    }
}
我的日志(不包括整个base64)

11-15 11:46:25.565 19702-19702/com.example.apostolis.gpsapi15 I/art:Late enabling-Xcheck:jni 11-15 11:46:25.597 19702-19702/com.example.apostolis.gpsapi15 W/System:ClassLoader 引用的未知路径: /data/app/com.example.apostolis.gpsapi15-1/lib/arm64 11-15 11:46:25.600 19702-19702/com.example.apostolis.gpsapi15 I/MultiDex:VM 版本2.1.0支持多索引11-15 11:46:25.600 19702-19702/com.example.apostolis.gpsapi15 I/MultiDex:安装11-15 11:46:25.600 19702-19702/com.example.apostolis.gpsapi15 I/MultiDex:VM 具有多索引支持,多索引支持库已禁用。11-15 11:46:25.60319702-19702/com.example.apostolis.gpsapi15 I/FirebaseInitProvider:FirebaseApp初始化未成功11-15 11:46:25.6161619702-19702/com.example.apostolis.gpsapi15 W/art:Before Android 4.1,方法Android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.UpdatentFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList、android.graphics.PorterDuff$模式) 将错误地重写中的包私有方法 android.graphics.drawable.drawable 11-15 11:46:25.622 19702-19702/com.example.apostolis.gpsapi15 D/PhoneWindow:state.preset =假,颜色:0,半透明=0 11-15 11:46:25.622 19702-19702/com.example.apostolis.gpsapi15 D/PhoneWindow:state.preset =假,颜色:0,半透明=0 11-15 11:46:25.622 19702-19702/com.example.apostolis.gpsapi15 D/PhoneWindow:state.preset =假,颜色:0,半透明=0 11-15 11:46:25.624 19702-19702/com.example.apostolis.gpsapi15 D/PhoneWindow:state.preset =假,颜色:-16777216,半透明=0 11-15 11:46:25.629 19702-19702/com.example.apostolis.gpsapi15 V/BoostFramework: mAcquireFunc方法=公共整数 com.qualcomm.qti.Performance.perfLockAcquire(int,int[])11-15 11:46:25.63019702-19702/com.example.apostolis.gpsapi15 V/BoostFramework:mReleaseFunc方法=public int com.qualcomm.qti.Performance.perfLockRelease()11-15 11:46:25.630 19702-19702/com.example.apostolis.gpsapi15 V/BoostFramework: mAcquireTouchFunc方法=公共整数 com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[]) 11-15 11:46:25.63019702-19702/com.example.apostolis.gpsapi15 V/BoostFramework:mIOPStart方法=public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String) 11-15 11:46:25.63019702-19702/com.example.apostolis.gpsapi15 V/BoostFramework:mIOPStop方法=public int com.qualcomm.qti.Performance.perfioprefetchtstop()11-15 11:46:25.632 19702-19702/com.example.apostolis.gpsapi15 V/BoostFramework: BoostFramework():mPerf=com.qualcomm.qti。Performance@5ec1d49 11-15 11:46:25.63219702-19702/com.example.apostolis.gpsapi15 V/BoostFramework:BoostFramework():mPerf= com.qualcomm.qti。Performance@5eae64e 11-15 11:46:25.655 19702-19702/com.example.apostolis.gpsapi15 D/AppTracker:App事件: 开始11-15 11:46:25.66219702-19717/com.example.apostolis.gpsapi15 D/OpenGLRenderer:使用EGL\u交换\u行为\u保留:真11-15 11:46:25.667 19702-19702/com.example.apostolis.gpsapi15 D/AppTracker: 应用程序事件:停止11-15 11:46:25.684 19702-19702/com.example.apostolis.gpsapi15 D/PhoneWindow:state.preset =真,颜色:-16777216,半透明=0 11-15 11:46:25.708 19702-19717/com.example.apostolis.gpsapi15 I/Adreno:QUALCOMM build
:19f8f74,Iac38d51750 建造日期:2016年6月6日 OpenGL ES着色器编译器版本:XE031.07.00.01 当地分支机构:案例2489916\u取消映射\u崩溃 远程分支: 远程分支: 重建分支:11-15 11:46:25.712 19702-19717/com.example.apostolis.gpsapi15 I/OpenGLRenderer: 已初始化EGL,版本1.4 11-15 11:46:25.721 19702-19702/com.example.apostolis.gpsapi15 D/AbstractTracker:事件 成功11-15 11:46:25.725 19702-19702/com.example.apostolis.gpsapi15 D/AbstractTracker:事件成功11-15 11:46:25.740 19702-19717/com.example.apostolis.gpsapi15 E/HAL:负载: 格拉洛克msm8996.so 11-15 11:46:37.663 19702-19702/com.example.apostolis.gpsapi15 D/AppTracker:App事件: 开始11-15 11:46:37.705 19702-19702/com.example.apostolis.gpsapi15 D/AbstractTracker:事件成功11-15 11:46:38.715 19702-19702/com.example.apostolis.gpsapi15 D/LocationManager: 请求位置更新 listener=com.example.apostolis.gpsapi15。GPSTracker@f1972c8 packageName=com.example.apostolis.gpsapi15 11-15 11:46:38.718 19702-19702/com.example.apostolis.gpsapi15 D/网络:网络11-15 11:46:38.735 19702-19702/com.example.apostolis.gpsapi15 D/AppTracker: 应用程序事件:停止11-15 11:46:38.749 19702-19702/com.example.apostolis.gpsapi15 D/PhoneWindow:state.preset =假,颜色:0,半透明=0 11-15 11:46:38.749 19702-19702/com.exampl
byte[] fullyReadFileToBytes(File f) throws IOException {
        int size = (int) f.length();
        byte bytes[] = new byte[size];
        byte tmpBuff[] = new byte[size];
        FileInputStream fis= new FileInputStream(f);;
        try {
            int read = fis.read(bytes, 0, size);
            if (read < size) {
                int remain = size - read;
                while (remain > 0) {
                    read = fis.read(tmpBuff, 0, remain);
                    System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                    remain -= read;
                }
            }
        }  catch (IOException e){
            throw e;
        } finally {
            fis.close();
        }

        return bytes;
    }
byte[] byteArray = fullyReadFileToBytes(imageFile);
Log.d("Activity", "Byte array: "+ Arrays.toString(byteArray));`