문제

웹 서버에서 이미지를 다운로드하고 화면에 표시하는 기능을 수행하고 있으며 사용자가 이미지를 유지하려면 특정 폴더의 SD 카드에 이미지를 저장합니다. 비트 맵을 가져 와서 내가 선택한 폴더의 SD 카드에 저장하는 쉬운 방법이 있습니까?

내 문제는 이미지를 다운로드하여 화면에 비트 맵으로 표시 할 수 있다는 것입니다. 이미지를 특정 폴더에 저장하는 유일한 방법은 FileOutputStream을 사용하는 것이지만 바이트 배열이 필요합니다. 비트 맵에서 바이트 배열로 변환하는 방법 (올바른 방법이라면)을 확실히 잘 모르겠으므로 FileOutputStream을 사용하여 데이터를 작성할 수 있습니다.

내가 가진 다른 옵션은 Medicstore를 사용하는 것입니다.

MediaStore.Images.Media.insertImage(getContentResolver(), bm,
    barcodeNumber + ".jpg Card Image", barcodeNumber + ".jpg Card Image");

SD 카드에 저장하는 데 적합하지만 폴더를 사용자 정의 할 수는 없습니다.

도움이 되었습니까?

해결책

try (FileOutputStream out = new FileOutputStream(filename)) {
    bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
    // PNG is a lossless format, the compression factor (100) is ignored
} catch (IOException e) {
    e.printStackTrace();
}

다른 팁

당신은 사용해야합니다 Bitmap.compress() 비트 맵을 파일로 저장하는 메소드. 사용 된 형식이 허용되는 경우 (허용되는 경우) 사진을 획득하고 출력 스트림으로 밀어 넣습니다.

다음은 getImageBitmap(myurl) 압축 속도가 85% 인 JPEG로 압축 될 수 있습니다.

// Assume block needs to be inside a Try/Catch block.
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
Integer counter = 0;
File file = new File(path, "FitnessGirl"+counter+".jpg"); // the File to save , append increasing numeric counter to prevent files from getting overwritten.
fOut = new FileOutputStream(file);

Bitmap pictureBitmap = getImageBitmap(myurl); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut); // saving the Bitmap to a file compressed as a JPEG with 85% compression rate
fOut.flush(); // Not really required
fOut.close(); // do not forget to close the stream

MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
outStream = new FileOutputStream(file);

AndroidManifest.xml (적어도 OS2.2)에서 허가없이 예외를 던집니다.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

내부에 onActivityResult:

String filename = "pippo.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);

Bitmap bitmap = (Bitmap)data.getExtras().get("data");
try {
     FileOutputStream out = new FileOutputStream(dest);
     bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
     out.flush();
     out.close();
} catch (Exception e) {
     e.printStackTrace();
}

무손실 인 PNG와 같은 일부 형식은 품질 설정을 무시합니다.

Bitmap bbicon;

bbicon=BitmapFactory.decodeResource(getResources(),R.drawable.bannerd10);
//ByteArrayOutputStream baosicon = new ByteArrayOutputStream();
//bbicon.compress(Bitmap.CompressFormat.PNG,0, baosicon);
//bicon=baosicon.toByteArray();

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "er.PNG");
try {
    outStream = new FileOutputStream(file);
    bbicon.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    outStream.flush();
    outStream.close();
} catch(Exception e) {

}

파일에 비트 맵을 저장하기위한 샘플 코드는 다음과 같습니다.

public static File savebitmap(Bitmap bmp) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
    File f = new File(Environment.getExternalStorageDirectory()
            + File.separator + "testimage.jpg");
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
    fo.close();
    return f;
}

이제 비트 맵을 내부 메모리에 저장하려면이 기능을 호출하십시오.

File newfile = savebitmap(bitmap);

도움이되기를 바랍니다. 행복한 코딩 생활.

왜 전화하지 마십시오 Bitmap.compress 100이있는 방법 (무손실 한 것처럼 들리는 소리)?

나는 또한 사진을 저장하고 싶습니다. 그러나 내 문제 (?)는 내가 그려진 비트 맵에서 저장하고 싶다는 것입니다.

나는 이것처럼 만들었다 :

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.save_sign:      

                myView.save();
                break;

            }
            return false;    

    }

public void save() {
            String filename;
            Date date = new Date(0);
            SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
            filename =  sdf.format(date);

            try{
                 String path = Environment.getExternalStorageDirectory().toString();
                 OutputStream fOut = null;
                 File file = new File(path, "/DCIM/Signatures/"+filename+".jpg");
                 fOut = new FileOutputStream(file);

                 mBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                 fOut.flush();
                 fOut.close();

                 MediaStore.Images.Media.insertImage(getContentResolver()
                 ,file.getAbsolutePath(),file.getName(),file.getName());

            }catch (Exception e) {
                e.printStackTrace();
            }

 }

PNG와 투명성을 보내는 방식.

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                    "/CustomDir";
File dir = new File(file_path);
if(!dir.exists())
  dir.mkdirs();

String format = new SimpleDateFormat("yyyyMMddHHmmss",
       java.util.Locale.getDefault()).format(new Date());

File file = new File(dir, format + ".png");
FileOutputStream fOut;
try {
        fOut = new FileOutputStream(file);
        yourbitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
     } catch (Exception e) {
        e.printStackTrace();
 }

Uri uri = Uri.fromFile(file);     
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
intent.putExtra(Intent.EXTRA_STREAM, uri);

startActivity(Intent.createChooser(intent,"Sharing something")));

비디오의 비디오 썸네일을 만듭니다. 비디오가 손상되거나 형식이 지원되지 않으면 NULL을 반환 할 수 있습니다.

private void makeVideoPreview() {
    Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(videoAbsolutePath, MediaStore.Images.Thumbnails.MINI_KIND);
    saveImage(thumbnail);
}

sdcard에 비트 맵을 저장하려면 다음 코드를 사용하십시오.

저장 이미지

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

이미지 저장 경로를 얻으려면

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

이봐, 그냥 이름을주세요 .BMP

이 작업을 수행:

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);

//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "**test.bmp**")

내가 바보처럼 들리는 소리가 들리지만 일단 시도해 보면 BMP foramt에서 저장 될 것입니다.

전화하기 전에 디렉토리가 생성되어 있는지 확인하십시오 bitmap.compress:

new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();

Android 4.4 Kitkat 이후, 2017 년 현재 Android 4.4 이상의 점유율은 약 20% 이하이며 감소하면 SD 카드에 저장할 수 없습니다. File 수업 및 getExternalStorageDirectory() 방법. 이 메소드는 장치 내부 메모리를 반환하고 이미지를 모든 앱에 표시합니다. 또한 앱에 비공개로만 이미지를 저장하고 사용자가 앱을 삭제할 때 삭제할 수 있습니다. openFileOutput() 방법.

Android 6.0을 시작으로 SD 카드를 내부 메모리로 포맷 할 수 있지만 장치에 대한 비공개로만 지정할 수 있습니다. (SD 차량을 내부 메모리로 포맷하는 경우 장치 만 액세스하거나 내용을 볼 수 있습니다) 해당 SD 카드에 저장할 수 있습니다. 다른 답변이지만 탈착식 SD 카드를 사용하려면 아래의 답변을 읽어야합니다.

당신은 사용해야합니다 스토리지 액세스 프레임 워크 URI를 폴더로 가져 오기 위해 onActivityResult 활동 방법 사용자가 폴더를 선택하고 사용자가 장치를 다시 시작한 후 폴더에 액세스 할 수 있도록 RetReive 지속 가능한 권한을 추가하십시오.

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

    if (resultCode == RESULT_OK) {

        // selectDirectory() invoked
        if (requestCode == REQUEST_FOLDER_ACCESS) {

            if (data.getData() != null) {
                Uri treeUri = data.getData();
                tvSAF.setText("Dir: " + data.getData().toString());
                currentFolder = treeUri.toString();
                saveCurrentFolderToPrefs();

                // grantUriPermission(getPackageName(), treeUri,
                // Intent.FLAG_GRANT_READ_URI_PERMISSION |
                // Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                final int takeFlags = data.getFlags()
                        & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // Check for the freshest data.
                getContentResolver().takePersistableUriPermission(treeUri, takeFlags);

            }
        }
    }
}

이제 폴더 저장 폴더 저장 공유 환경 설정에 저장 이미지를 저장할 때마다 사용자에게 폴더를 선택하도록 요청하지 마십시오.

당신은 사용해야합니다 DocumentFile 이미지를 저장하는 클래스 File 또는 ParcelFileDescriptor, 자세한 정보는 확인할 수 있습니다 이 스레드 SD 카드에 이미지를 저장합니다 compress(CompressFormat.JPEG, 100, out); 방법 및 DocumentFile 클래스.

선택한 디렉토리에 비트 맵을 저장하려고합니다. 사용자가 BitMaps/Drawables/Base64 이미지를로드, 저장 및 변환 할 수있는 라이브러리 ImageWorker를 만들었습니다.

Min SDK -14

전제 조건

  • 파일을 저장하려면 write_external_storage 권한이 필요합니다.
  • 파일을 검색하려면 read_external_storage 권한이 필요합니다.

비트 맵 절약/드로우 가능/base64

ImageWorker.to(context).
    directory("ImageWorker").
    subDirectory("SubDirectory").
    setFileName("Image").
    withExtension(Extension.PNG).
    save(sourceBitmap,85)

로드 비트 맵

val bitmap: Bitmap? = ImageWorker.from(context).
    directory("ImageWorker").
    subDirectory("SubDirectory").
    setFileName("Image").
    withExtension(Extension.PNG).
    load()

구현

종속성을 추가하십시오

프로젝트 수준 Gradle에서

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

응용 프로그램 레벨 Gradle

dependencies {
            implementation 'com.github.1AboveAll:ImageWorker:0.51'
    }

더 읽을 수 있습니다 https://github.com/1aboveall/imageworker/blob/master/readme.md

일부 새로운 장치는 비트 맵을 저장하지 않으므로 조금 더 설명했습니다.

추가했는지 확인하십시오 아래의 허가

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

아래에서 XML 파일을 만듭니다 xml 폴더 이름 Provider_Paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="." />
</paths>

그리고 AndroidManifest에서

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

그런 다음 SaveBitMapFile (PassYourbitmaphere)을 호출하십시오.

public static void saveBitmapFile(Bitmap bitmap) throws IOException {
        File mediaFile = getOutputMediaFile();
        FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, getQualityNumber(bitmap), fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    }

어디

File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment.getExternalStorageDirectory(),
                "easyTouchPro");
        if (mediaStorageDir.isDirectory()) {

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(Calendar.getInstance().getTime());
            String mCurrentPath = mediaStorageDir.getPath() + File.separator
                            + "IMG_" + timeStamp + ".jpg";
            File mediaFile = new File(mCurrentPath);
            return mediaFile;
        } else { /// error handling for PIE devices..
            mediaStorageDir.delete();
            mediaStorageDir.mkdirs();
            galleryAddPic(mediaStorageDir);

            return (getOutputMediaFile());
        }
    }

그리고 다른 방법

public static int getQualityNumber(Bitmap bitmap) {
        int size = bitmap.getByteCount();
        int percentage = 0;

        if (size > 500000 && size <= 800000) {
            percentage = 15;
        } else if (size > 800000 && size <= 1000000) {
            percentage = 20;
        } else if (size > 1000000 && size <= 1500000) {
            percentage = 25;
        } else if (size > 1500000 && size <= 2500000) {
            percentage = 27;
        } else if (size > 2500000 && size <= 3500000) {
            percentage = 30;
        } else if (size > 3500000 && size <= 4000000) {
            percentage = 40;
        } else if (size > 4000000 && size <= 5000000) {
            percentage = 50;
        } else if (size > 5000000) {
            percentage = 75;
        }

        return percentage;
    }

그리고

void galleryAddPic(File f) {
        Intent mediaScanIntent = new Intent(
                "android.intent.action.MEDIA_SCANNER_SCAN_FILE");
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);

        this.sendBroadcast(mediaScanIntent);
    }

실제로 답이 아니라 의견입니다. 에뮬레이터 환경을 실행하는 Mac에 있고 java.io.ioexception : 권한 거부 -이 코드의 오류 :이 코드 :

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    Log.d("DEBUG", "onActivityResult called");
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    if(requestCode == 0 && resultCode == RESULT_OK) {
        Log.d("DEBUG", "result is ok");
        try{
            Bitmap map = (Bitmap) imageReturnedIntent.getExtras().get("data");
            File sd = new File(Environment.getExternalStorageDirectory(), "test.png");
            sd.mkdirs();
            sd.createNewFile();
            FileOutputStream out = new FileOutputStream(sd);
            map.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch(FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

또한 Manifest 파일 (다른 사람들이 언급 한 바와 같이)에 use-permission android.permission.write_external_storage를 추가했습니다.

압축하지 않고 갤러리에 비트 맵을 저장하십시오.

private File saveBitMap(Context context, Bitmap Final_bitmap) {
    File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Your Folder Name");
    if (!pictureFileDir.exists()) {
        boolean isDirectoryCreated = pictureFileDir.mkdirs();
        if (!isDirectoryCreated)
            Log.i("TAG", "Can't create directory to save the image");
        return null;
    }
    String filename = pictureFileDir.getPath() + File.separator + System.currentTimeMillis() + ".jpg";
    File pictureFile = new File(filename);
    try {
        pictureFile.createNewFile();
        FileOutputStream oStream = new FileOutputStream(pictureFile);
        Final_bitmap.compress(Bitmap.CompressFormat.PNG, 100, oStream);
        oStream.flush();
        oStream.close();
        Toast.makeText(Full_Screen_Activity.this, "Save Image Successfully..", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TAG", "There was an issue saving the image.");
    }
    scanGallery(context, pictureFile.getAbsolutePath());
    return pictureFile;
}
private void scanGallery(Context cntx, String path) {
    try {
        MediaScannerConnection.scanFile(cntx, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Toast.makeText(Full_Screen_Activity.this, "Save Image Successfully..", Toast.LENGTH_SHORT).show();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        Log.i("TAG", "There was an issue scanning gallery.");
    }
}

// | == | BitMap에서 PNG 파일을 만듭니다.

void devImjFylFnc(String pthAndFylTtlVar, Bitmap iptBmjVar)
{
    try
    {
        FileOutputStream fylBytWrtrVar = new FileOutputStream(pthAndFylTtlVar);
        iptBmjVar.compress(Bitmap.CompressFormat.PNG, 100, fylBytWrtrVar);
        fylBytWrtrVar.close();
    }
    catch (Exception errVar) { errVar.printStackTrace(); }
}

// | == | 파일에서 BIMAP 가져 오기 :

Bitmap getBmjFrmFylFnc(String pthAndFylTtlVar)
{
    return BitmapFactory.decodeFile(pthAndFylTtlVar);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top