Zunächst ist Ihre Rückgabe ungültig, weil Glide die Anforderung in einem asynchronen Thread ausführt. So wird byteArrayOutputStream
nie rechtzeitig gefüllt, bevor die Funktion zurückkehrt. Dies bedeutet, dass Ihre Funktion immer ein leeres Byte-Array zurückgibt. Dies bedeutet auch, dass Ihre Log-Anweisung Log.d(TAG, String.format("Got image bytes: %d for %s", byteArrayOutputStream.size(), pictureURL));
ungültig ist. Wenn Sie dies wissen, wird Ihr nach Got image bytes...
angezeigt. Sie müssen Ihren Code neu formatieren, um Callbacks zu verwenden, um den Aufrufer der Funktion zu benachrichtigen, dass Ihr Code das Array abgerufen hat. Etwas wie folgt aus:
public interface GlideByteLoadCallback {
void onBytesExtracted(byte[] bytes);
void onFail(String message);
}
public void extractImageFromCache(Context context, String pictureURL, GlideByteLoadCallback callback) {
if (context != null && pictureURL != null && !pictureURL.isEmpty()) {
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Glide.with(context)
.load(pictureURL)
.asBitmap()
.toBytes()
.diskCacheStrategy(DiskCacheStrategy.SOURCE) // Load the original hires image
.into(new SimpleTarget<byte[]>() {
@Override public void onResourceReady(final byte[] resource, GlideAnimation<? super byte[]> glideAnimation) {
Log.d(TAG, "About to start extraction");
new AsyncTask<Void, Void, Void>() {
@Override protected Void doInBackground(Void... params) {
Log.d(TAG, "Start extraction");
try {
Log.d(TAG, "Image bytes len: " + resource.length);
byteArrayOutputStream.write(resource);
byteArrayOutputStream.flush();
if (callback != null) callback.onBytesExtracted(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "Unable to load image: " + pictureURL);
e.printStackTrace();
if (callback != null) callback.onFail("Extraction failed");
}
}
}.execute();
}
});
}
if (callback != null) callback.onFail("Invalid url");
}
Dann rufen Sie es mit:
extractImageFromCache(context, picture, new GlideByteLoadCallback() {
@Override
public void onFail(String message) {
// handle failure here
}
@Override
public void onBytesExtracted(byte[] bytes) {
// do stuff with bytes here
}
});
Können Sie den Logcat posten? – azizbekian
Wo nennst du diese Funktion? – rom4ek
Erwähnen Glide-Version, ich habe Ihren Code versucht und es funktioniert perfekt in 'gleiten: 3.7.0' – Maddy